Ejemplo n.º 1
0
def pacmanSuccessorStateAxioms(x, y, t, walls_grid):
    """
    Successor state axiom for state (x,y,t) (from t-1), given the board (as a 
    grid representing the wall locations).
    Current <==> (previous position at time t-1) & (took action to move to x, y)
    """
    "*** YOUR CODE HERE ***"
    successor_list = []
    if 0 <= x - 1 < walls_grid.width and 0 <= y < walls_grid.height:
        if not walls_grid.data[x - 1][y]:
            location = logic.PropSymbolExpr('P', x - 1, y, t - 1)
            action = logic.PropSymbolExpr('East', t - 1)
            successor_list.append(location & action)
    if 0 <= x + 1 < walls_grid.width and 0 <= y < walls_grid.height:
        if not walls_grid.data[x + 1][y]:
            location = logic.PropSymbolExpr('P', x + 1, y, t - 1)
            action = logic.PropSymbolExpr('West', t - 1)
            successor_list.append(location & action)
    if 0 <= x < walls_grid.width and 0 <= y - 1 < walls_grid.height:
        if not walls_grid.data[x][y - 1]:
            location = logic.PropSymbolExpr('P', x, y - 1, t - 1)
            action = logic.PropSymbolExpr('North', t - 1)
            successor_list.append(location & action)
    if 0 <= x < walls_grid.width and 0 <= y + 1 < walls_grid.height:
        if not walls_grid.data[x][y + 1]:
            location = logic.PropSymbolExpr('P', x, y + 1, t - 1)
            action = logic.PropSymbolExpr('South', t - 1)
            successor_list.append(location & action)
    return logic.PropSymbolExpr('P', x, y, t) % logic.associate(
        '|', successor_list)
Ejemplo n.º 2
0
def atMostOne(expressions) :
    """
    Given a list of logic.Expr instances, return a single logic.Expr instance in CNF (conjunctive normal form)
    that represents the logic that at most one of the expressions in the list is true.
    """
    "*** YOUR CODE HERE ***"
    
    exprCNF = ~(atLeastOne(expressions))
    
    i = 0

    while i < len(expressions):
        j = 0
        exprAtMostOne = []

        while j < len(expressions):

            if expressions[j] == expressions[i]:
                exprAtMostOne.append(expressions[j])

            else:
                exprAtMostOne.append(~expressions[j])
            j = j + 1

        exprCNF = exprCNF | logic.associate('&', exprAtMostOne)
        i = i + 1

    #print exprCNF

    return exprCNF
Ejemplo n.º 3
0
def generate_initial_statements(problem):
    temp_list = []
    initial_position_expr = logic.PropSymbolExpr("P", start[0], start[1], time)
    for x in range(0, problem.getWidth()):
        for y in range(0, problem.getHeight()):
            if (x,y) == (start[0], start[1]):
                continue
            else:
                temp_list.append(logic.PropSymbolExpr("P", x, y, time))
    initial_position_expr = initial_position_expr & ~(logic.associate('|', temp_list))
    return initial_position_expr
Ejemplo n.º 4
0
 def result(self, state, action):
     terms = parse_state(state)
     sentence = str(
         logic.associate(
             '&',
             action(logic.conjuncts(state), action.args).clauses))
     #print('------------\nBefore: ' + sentence)
     while sentence.find('divide(x)') != -1:
         quotient = terms[4] / terms[0]
         terms[0] = 1
         terms[4] = quotient
         sentence = sentence.replace('divide(x)', '{:.2f}'.format(quotient))
     while sentence.find('combine') != -1:
         start = sentence.find('combine')
         term = int(sentence[start + 9]) - 1
         if term < 3:
             new_val = terms[term] + terms[2]
             terms[term] = new_val
             terms[2] = 0
         else:
             new_val = terms[term] + terms[5]
             terms[term] = new_val
             terms[5] = 0
         sentence = sentence.replace(sentence[start:(start + 11)],
                                     str(new_val))
     while sentence.find('inverse') != -1:
         start = sentence.find('inverse')
         term = int(sentence[start + 9]) - 1
         new_val = -1 * terms[term]
         if term == 3:
             terms[2] = new_val
         elif term == 1:
             terms[5] = new_val
         terms[term] = 0
         sentence = sentence.replace(sentence[start:(start + 11)],
                                     str(new_val))
     #print('After: ' + sentence + '\n------------')
     return logic.associate('&', self.convert(sentence.replace('Not', '~')))
Ejemplo n.º 5
0
def atLeastOne(expressions) :
    """
    Given a list of logic.Expr instances, return a single logic.Expr instance in CNF (conjunctive normal form)
    that represents the logic that at least one of the expressions in the list is true.
    >>> A = logic.PropSymbolExpr('A');
    >>> B = logic.PropSymbolExpr('B');
    >>> symbols = [A, B]
    >>> atleast1 = atLeastOne(symbols)
    >>> model1 = {A:False, B:False}
    >>> print logic.pl_true(atleast1,model1)
    False
    >>> model2 = {A:False, B:True}
    >>> print logic.pl_true(atleast1,model2)
    True
    >>> model3 = {A:True, B:True}
    >>> print logic.pl_true(atleast1,model2)
    True
    """
    "*** YOUR CODE HERE ***"

    return logic.associate('|', expressions)
Ejemplo n.º 6
0
def positionLogicPlan(problem):
    """
    Given an instance of a PositionSearchProblem, return a list of actions that lead to the goal.
    Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST}
    Note that STOP is not an available action.


    destination_time1 <=> (src1_time0 & action1_time0) | src2_time0 & action2_0) |(src3_time0 & action3_time0)
and your goal state can just be like:
goal_timeT
then you plug it in for each value of time (0-50)

    """

    "*** YOUR CODE HERE ***"
    cnf = []
    maxTime = 51
    n = Directions.NORTH
    s = Directions.SOUTH
    e = Directions.EAST
    w = Directions.WEST
    DirectionsList = [n, s, e , w]
    width = problem.getWidth()+1
    height = problem.getHeight()+1

    for time in range(0, maxTime):
        stateLogicList = []

        if time == 0: #Only need Start/Goal
            # Start State
            startState = problem.getStartState()
            pacmanStart = logic.PropSymbolExpr("P", startState[0], startState[1], 0)
            nonStartStates = []
            for x in range(1, width):
                for y in range(1, height):
                    if (x,y) == (startState[0], startState[1]):
                        continue
                    else
                        nonStartStates.append(logic.PropSymbolExpr("P", x, y, 0))

            startLogic = logic.to_cnf(pacmanStart & ~(logic.associate('|', nonStartStates)))
            cnf.append(startLogic)

        else:
            for x in range(1,width):
                for y in range(1, height):
                    currentState = (x,y)
                    currentLogic = logic.PropSymbolExpr("P", currentState[0], currentState[1], time)
                    for action in problem.actions(currentState):
                        if action == n:
                            nextstate = problem.result(currentState, action)[0]
                            logic.PropSymbolExpr("P", x, y+1, time-1)
                            nextaction = logic.PropSymbolExpr(s, time-1)
                        elif action == s:
                            nextstate = logic.PropSymbolExpr("P", x, y-1, time-1)
                            nextaction = logic.PropSymbolExpr(n, time-1)
                        elif action == e:
                            nextstate = logic.PropSymbolExpr("P", x+1, y, time-1)
                            nextaction = logic.PropSymbolExpr(w, time-1)
                        elif action == w:
                            nextstate = logic.PropSymbolExpr("P", x-1, y, time-1)
                            nextaction = logic.PropSymbolExpr(e, time-1)
                        stateLogicList.append((currentLogic, (nextstate &  nextaction)))

        dictionary = {}
        for elem in stateLogicList:
            if elem[0] not in dictionary.keys():
                dictionary[elem[0]] = [elem[1]]
            if elem[0] in dictionary.keys():
                dictionary[elem[0]].append(elem[1])

        for key in dictionary.keys():
            val = dictionary[key]    
            parents = logic.associate('|', val)
            cnf.append(logic.to_cnf(key % parents))

        # exactly one action is taken at one time
        Dir = []
        for direction in DirectionsList:
            Dir.append(logic.PropSymbolExpr(direction, time))
        OneMove = exactlyOne(Dir)
        cnf.append(logic.to_cnf(OneMove))

        #Goal State
        goalState = problem.getGoalState()
        cnf.append(logic.to_cnf(logic.PropSymbolExpr("P", goalState[0], goalState[1], time))) 
        model = logic.pycoSAT(cnf)
        if model:
            return extractActionSequence(model, DirectionsList)
        #remove goal if the model is false
        cnf.remove(logic.PropSymbolExpr("P", goalState[0], goalState[1], time))
Ejemplo n.º 7
0
    def get_next_action(self, observation):
        # get observation for the current state and return next action to apply (and None if no action is applicable)
        #observation is a dictionary with spaceship_name:number_of_laser_around it.

        global my_world
        print("my_world_is:")
        print(my_world)

        print("this is the observation:")
        print(observation)

        spaceships = my_world[0]
        devices = my_world[1]
        all_targets = my_world[2]

        #update spaceships and devices if there is spaceship that exploded
        for device in devices:
            if device[0] in observation:
                ship_name = device[0]
                if observation[ship_name] == -1:  #ship exploded
                    temp_list = list(devices)
                    temp_list.remove(device)
                    devices = tuple(temp_list)
        for ship in spaceships:
            if ship[0] in observation:
                ship_name = ship[0]
                if observation[ship_name] == -1:  # ship exploded
                    temp_list = list(spaceships)
                    temp_list.remove(ship)
                    spaceships = tuple(temp_list)
        #updated world after removing ships that exploded. important for the GBFS running in the next lines
        my_world = (spaceships, devices, all_targets)

        #all ships exploded
        if not devices or not spaceships:
            return None

        ##########################
        #running GBFS from current world
        p = SpaceshipProblem(my_world)
        timeout = 60
        result = check_problem(
            p, (lambda p: search.best_first_graph_search(p, p.h)), timeout)
        print("GBFS ", result)
        ##########################

        #updating the world representation
        next_action = result[2][0]

        if next_action[0] in ("turn_on", "use", "calibrate"):
            self.update_my_world(next_action)
            return next_action

        #for all locations without lasers, make a tuple of their neighbors and mark them as safe - without lasers.
        all_neighbors = ()
        all_neighbors = (next_action[2], ) + all_neighbors
        for sname, nb_lasers in observation.items():
            if nb_lasers == 0:
                for shipname, location in spaceships:
                    if shipname == sname:
                        ship_all_neighbors = self.get_neighbors(location)
                        for i in ship_all_neighbors:
                            if i not in all_neighbors:
                                all_neighbors = (i, ) + all_neighbors
        for i in all_neighbors:
            self.lasers_logic.tell(~(self.grid_dict[i]))

        #if the action is move for some ship and there isn't lasers around it, go ahead and do it.
        for sname, nb_lasers in observation.items():
            if next_action[1] == sname and nb_lasers == 0 and next_action[
                    0] == "move":
                self.update_my_world(next_action)
                return next_action

        #if the code is here, then the gbfs wants to move a ship with lasers around it
        #next_action[0] = "move", next_action[1] = ship name, next_action[2] = from, next_action[3] = to
        n_combinations = []
        for ship_name, ship_location in spaceships:
            if ship_name == next_action[1]:
                near_by_n = self.get_neighbors(ship_location)
                near_by_n = (ship_location, ) + near_by_n
                nb_lasers = observation[ship_name]
                n_combinations = (itertools.combinations(
                    list(near_by_n),
                    len(near_by_n) - nb_lasers))
        combination_list = list(n_combinations)
        small_combinations = (combination_list[0], combination_list[1],
                              combination_list[2])
        logic_list = []
        for combination in small_combinations:
            temp = []
            for coord in combination:
                temp.append(~self.grid_dict[coord])
            logic_list.append(logic.associate('&', temp))

        self.lasers_logic.tell(logic.associate('|', logic_list))
        logic_answer = logic.dpll_satisfiable(
            logic.to_cnf(logic.associate('&', self.lasers_logic.clauses)))
        #logic answer contains a dict of Lxyz = Flase/True. when False means that the (x,y,z) location is safe, and unsafe
        #(contains lasers) otherwise
        #if "to_location" of GBFS is in logic_answer and is false - use it,
        #else we would like to choose a random one that is not our current location

        print("logic answer:", logic_answer)
        # gbfs_to_location = self.grid_dict[next_action[3]]

        # logic_answer.delete(self.grid_dict[next_action[2]])
        for k, v in logic_answer.items():
            if v == True:
                logic_answer = self.minus_key(k, logic_answer)
        #remove from logic answer not neighbors
        nears = ()
        neighbors = self.get_neighbors(next_action[2])
        for n in neighbors:
            temp = self.grid_dict[n]
            nears = (temp, ) + nears
        for l in logic_answer:
            if l not in nears:
                logic_answer = self.minus_key(l, logic_answer)
        #remove targets locations
        for t in all_targets:
            temp = self.grid_dict[t]
            if temp in logic_answer:
                logic_answer = self.minus_key(temp, logic_answer)
        #remove spaceships locations
        for ship_name, location in spaceships:
            temp = self.grid_dict[location]
            if temp in logic_answer:
                logic_answer = self.minus_key(temp, logic_answer)

        print("whats left for random: ", list(logic_answer.keys()))
        random_to_location = random.choice(list(logic_answer.keys()))
        print("random choise:", random_to_location)
        if not random_to_location:  #empty
            return None
        #return Lxyz form to (x,y,z)
        new_to_location = ()
        for k, v in self.grid_dict.items():
            if v == random_to_location:
                new_to_location = k
        print("new_to_location:", new_to_location)
        new_next_action = ("move", next_action[1], next_action[2],
                           new_to_location)
        print("new next location", new_next_action)
        self.update_my_world(new_next_action)
        return new_next_action
Ejemplo n.º 8
0
import logic

if __name__ == '__main__':

    wumpus_kb = logic.PropKB()
    P11, P12, P21, P22, P31, B11, B21 = logic.expr(
        'P11, P12, P21, P22, P31, B11, B21')
    #B100 = logic.expr('B100')
    wumpus_kb.tell(~P11)
    wumpus_kb.tell(B11 | '<=>' | ((P12 | P21)))
    wumpus_kb.tell(B21 | '<=>' | ((P11 | P22 | P31)))
    wumpus_kb.tell(~B11)
    ship = (1, 23, 4)
    shipstr = 'P' + str((ship[0] + 1, ship[1], ship[2]))
    #for v in ship:
    #   shipstr += str(v)
    print(shipstr)
    wumpus_kb.tell(~logic.expr(shipstr))
    result = logic.dpll_satisfiable(
        logic.to_cnf(
            logic.associate('&', wumpus_kb.clauses + [logic.expr(P22)])))
    print(result)
    result = logic.dpll_satisfiable(
        logic.to_cnf(
            logic.associate('&', wumpus_kb.clauses + [logic.expr(shipstr)])))
    print(result)
Ejemplo n.º 9
0
def foodLogicPlan(problem):
    """
    Given an instance of a FoodSearchProblem, return a list of actions that help Pacman
    eat all of the food.
    Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST}
    Note that STOP is not an available action.
    """
    "*** YOUR CODE HERE ***"
    cnf = []
    maxTime = 51
    n = Directions.NORTH
    s = Directions.SOUTH
    e = Directions.EAST
    w = Directions.WEST
    DirectionsList = [n, s, e , w]
    width = problem.getWidth()+1
    height = problem.getHeight()+1
    #Starting State
    swag = problem.getStartState()
    startState = swag[0]
    #Get positions of food
    foodGrid = swag[1]
    foodPosList = []
    for x in range(width+1):
        for y in range(height+1):
            if foodGrid[x][y]:
                foodPosList.append((x,y))

    pacmanStart = logic.PropSymbolExpr("P", startState[0], startState[1], 0)
    nonStartStates = []
    for x in range(1, width):
        for y in range(1, height):
            if (x,y) == (startState[0], startState[1]):
                continue
            else:
                nonStartStates.append(logic.PropSymbolExpr("P", x, y, 0))
            startLogic = logic.to_cnf(pacmanStart & ~(logic.associate('|', nonStartStates)))
    cnf.append(startLogic)

    stateList = []
    for x in range(width+1):
        for y in range(height+1):
            if problem.isWall((x,y)):
                continue
            else:
                stateList.append((x,y))

    for time in range(maxTime):
        #print time
        oneStateList = []
        for state in stateList:
            oneStateList.append(logic.PropSymbolExpr("P",state[0],state[1], time))
            legalActionList = problem.actions((state, foodGrid))
            illegalList = []
            for action in DirectionsList:
                if action in legalActionList:
                    nextState = problem.result((state, foodGrid), action)[0][0]
                    # state & action >> new state
                    nextLogic = (logic.PropSymbolExpr("P",state[0],state[1], time) & logic.PropSymbolExpr(action,time)) >> logic.PropSymbolExpr('P',nextState[0],nextState[1], time+1)
                    cnf.append(logic.to_cnf(nextLogic))
                else:
                    illegalList.append(action)
            for action in illegalList:
                # state >> not illegal action
                cnf.append(logic.to_cnf(logic.PropSymbolExpr("P",state[0],state[1], time) >> ~logic.PropSymbolExpr(action,time)))

        # uses oneStateList, makes sure we are not in two places at once
        oneState = exactlyOne(oneStateList)
        cnf.append((oneState))
        
        # Exactly 1 move per turn
        Dir = []
        for direction in DirectionsList:
            Dir.append(logic.PropSymbolExpr(direction, time))
        oneMove = exactlyOne(Dir)
        cnf.append(logic.to_cnf(oneMove))

        # goal state (must hit each pellet once)
        foodAllEaten = []
        for food in foodPosList:
            foodOnce = []
            for alltime in range(time+1):
                foodOnce.append(logic.PropSymbolExpr('P',food[0],food[1],alltime))
            atLeastOnce = logic.associate('|', foodOnce)
            foodAllEaten.append(atLeastOnce)
        goalLogic = logic.associate('&', foodAllEaten)
        cnf.append(goalLogic)
        model = logic.pycoSAT(cnf)
        if model:
            path = extractActionSequence(model, DirectionsList)
            return path
        cnf.remove(goalLogic)
    print("you suck")
Ejemplo n.º 10
0
def foodGhostLogicPlan(problem):
    """
    Given an instance of a FoodGhostSearchProblem, return a list of actions that help Pacman
    eat all of the food and avoid patrolling ghosts.
    Ghosts only move east and west. They always start by moving East, unless they start next to
    and eastern wall. 
    Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST}
    Note that STOP is not an available action.
    """
    "*** YOUR CODE HERE ***"
    cnf = []
    maxTime = 51
    n = Directions.NORTH
    s = Directions.SOUTH
    e = Directions.EAST
    w = Directions.WEST
    DirectionsList = [n, s, e , w]
    width = problem.getWidth()+1
    height = problem.getHeight()+1
    #Starting State
    swag = problem.getStartState()
    startState = swag[0]
    ghostStartStateList = problem.getGhostStartStates()
    #Get positions of food
    foodGrid = swag[1]
    foodPosList = []
    for x in range(width+1):
        for y in range(height+1):
            if foodGrid[x][y]:
                foodPosList.append((x,y))

    pacmanStart = logic.PropSymbolExpr("P", startState[0], startState[1], 0)
    nonStartStates = []
    for x in range(1, width):
        for y in range(1, height):
            if (x,y) == (startState[0], startState[1]):
                continue
            else:
                nonStartStates.append(logic.PropSymbolExpr("P", x, y, 0))
            startLogic = logic.to_cnf(pacmanStart & ~(logic.associate('|', nonStartStates)))
    cnf.append(startLogic)

    stateList = []
    for x in range(width+1):
        for y in range(height+1):
            if problem.isWall((x,y)):
                continue
            else:
                stateList.append((x,y))

    for time in range(maxTime):
        oneStateList = []
        for state in stateList:
            oneStateList.append(logic.PropSymbolExpr("P",state[0],state[1], time))
            legalActionList = problem.actions((state, foodGrid))
            illegalList = []
            for action in DirectionsList:
                if action in legalActionList:
                    nextState = problem.result((state, foodGrid), action)[0][0]
                    # state & action >> new state
                    nextLogic = (logic.PropSymbolExpr("P",state[0],state[1], time) & logic.PropSymbolExpr(action,time)) >> logic.PropSymbolExpr('P',nextState[0],nextState[1], time+1)
                    cnf.append(logic.to_cnf(nextLogic))
                else:
                    illegalList.append(action)
            for action in illegalList:
                # state >> not illegal action
                cnf.append(logic.to_cnf(logic.PropSymbolExpr("P",state[0],state[1], time) >> ~logic.PropSymbolExpr(action,time)))

        # uses oneStateList, makes sure we are not in two places at once
        oneState = exactlyOne(oneStateList)
        cnf.append((oneState))
        
        # Exactly 1 move per turn
        Dir = []
        for direction in DirectionsList:
            Dir.append(logic.PropSymbolExpr(direction, time))
        oneMove = exactlyOne(Dir)
        cnf.append(logic.to_cnf(oneMove))

        # goal state (must hit each pellet once)
        foodAllEaten = []
        for food in foodPosList:
            foodOnce = []
            for alltime in range(time+1):
                foodOnce.append(logic.PropSymbolExpr('P',food[0],food[1],alltime))
            atLeastOnce = logic.associate('|', foodOnce)
            foodAllEaten.append(atLeastOnce)
        goalLogic = logic.associate('&', foodAllEaten)
        cnf.append(goalLogic)

        #Pacman and Ghost not in same place
        def ghostPositionfinder(ghoststart, time):
            ghostposition = ghoststart
            x = ghoststart[0]
            y = ghoststart[1]
            East = True
            for t in range(time):
                if East == True:
                    x += 1
                    if problem.isWall((x,y)):
                        x -= 2
                        East = False
                elif East == False:
                    x -= 1
                    if problem.isWall((x,y)):
                        x += 2
                        East = True
            return (x,y)
            #logic.PropSymbolExpr("G", ghostPos[0], ghostPos[1], 0)

        for ghostStartState in ghostStartStateList:
            ghostPos = ghostStartState.getPosition()
            ghostCurrentPos = ghostPositionfinder(ghostPos, time)
            cnf.append(logic.PropSymbolExpr("G", ghostCurrentPos[0], ghostCurrentPos[1], time))

        for pos in stateList:
            plsnodie = [logic.PropSymbolExpr("P",pos[0],pos[1],time)] + [logic.PropSymbolExpr("G",pos[0],pos[1],time)]
            cnf.append(atMostOne(plsnodie))
            plsnodie = [logic.PropSymbolExpr("P",pos[0],pos[1],time)] + [logic.PropSymbolExpr("G",pos[0],pos[1],time-1)]
            cnf.append(atMostOne(plsnodie))

        model = logic.pycoSAT(cnf)
        if model:
            path = extractActionSequence(model, DirectionsList)
            return path
        cnf.remove(goalLogic)

    print("you suck")
Ejemplo n.º 11
0
def positionLogicPlan(problem):
    """
    Given an instance of a PositionSearchProblem, return a list of actions that lead to the goal.
    Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST}
    Note that STOP is not an available action.
    """

    "*** YOUR CODE HERE ***"
    cnf = []
    maxTime = 51
    n = Directions.NORTH
    s = Directions.SOUTH
    e = Directions.EAST
    w = Directions.WEST
    DirectionsList = [n, s, e , w]
    width = problem.getWidth()+1
    height = problem.getHeight()+1
    #Starting State
    startState = problem.getStartState()
    pacmanStart = logic.PropSymbolExpr("P", startState[0], startState[1], 0)
    nonStartStates = []
    for x in range(1, width):
        for y in range(1, height):
            if (x,y) == (startState[0], startState[1]):
                continue
            else:
                nonStartStates.append(logic.PropSymbolExpr("P", x, y, 0))
            startLogic = logic.to_cnf(pacmanStart & ~(logic.associate('|', nonStartStates)))
    cnf.append(startLogic)

    goalState = problem.getGoalState()

    stateList = []
    for x in range(width+1):
        for y in range(height+1):
            if problem.isWall((x,y)):
                continue
            else:
                stateList.append((x,y))

    for time in range(maxTime):
        oneStateList = []
        for state in stateList:
            oneStateList.append(logic.PropSymbolExpr("P",state[0],state[1], time))
            legalActionList = problem.actions(state)
            illegalList = []
            for action in DirectionsList:
                if action in legalActionList:
                    nextState = problem.result(state, action)[0]
                    # state & action >> new state
                    nextLogic = (logic.PropSymbolExpr("P",state[0],state[1], time) & logic.PropSymbolExpr(action,time)) >> logic.PropSymbolExpr('P',nextState[0],nextState[1], time+1)
                    cnf.append(logic.to_cnf(nextLogic))
                else:
                    illegalList.append(action)
            for action in illegalList:
                # state >> not illegal action
                cnf.append(logic.to_cnf(logic.PropSymbolExpr('P',state[0],state[1], time) >> ~logic.PropSymbolExpr(action,time)))

        # uses oneStateList, makes sure we are not in two places at once
        oneState = exactlyOne(oneStateList)
        cnf.append((oneState))
        
        # Exactly 1 move per turn
        Dir = []
        for direction in DirectionsList:
            Dir.append(logic.PropSymbolExpr(direction, time))
        oneMove = exactlyOne(Dir)
        cnf.append(logic.to_cnf(oneMove))

        # goal state
        cnf.append(logic.PropSymbolExpr("P",goalState[0],goalState[1], time))

        #print time

        model = logic.pycoSAT(cnf)
        if model:
            path = extractActionSequence(model, DirectionsList)
            return path

        cnf.remove(logic.PropSymbolExpr("P",goalState[0],goalState[1], time))
Ejemplo n.º 12
0
def foodGhostLogicPlan(problem):
    """
    Given an instance of a FoodGhostSearchProblem, return a list of actions that help Pacman
    eat all of the food and avoid patrolling ghosts.
    Ghosts only move east and west. They always start by moving East, unless they start next to
    and eastern wall. 
    Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST}
    Note that STOP is not an available action.
    """
    "*** YOUR CODE HERE ***"
    cnf = []
    maxTime = 51
    n = Directions.NORTH
    s = Directions.SOUTH
    e = Directions.EAST
    w = Directions.WEST
    DirectionsList = [n, s, e, w]
    width = problem.getWidth() + 1
    height = problem.getHeight() + 1
    #Starting State
    swag = problem.getStartState()
    startState = swag[0]
    ghostStartStateList = problem.getGhostStartStates()
    #Get positions of food
    foodGrid = swag[1]
    foodPosList = []
    for x in range(width + 1):
        for y in range(height + 1):
            if foodGrid[x][y]:
                foodPosList.append((x, y))

    pacmanStart = logic.PropSymbolExpr("P", startState[0], startState[1], 0)
    nonStartStates = []
    for x in range(1, width):
        for y in range(1, height):
            if (x, y) == (startState[0], startState[1]):
                continue
            else:
                nonStartStates.append(logic.PropSymbolExpr("P", x, y, 0))
            startLogic = logic.to_cnf(
                pacmanStart & ~(logic.associate('|', nonStartStates)))
    cnf.append(startLogic)

    stateList = []
    for x in range(width + 1):
        for y in range(height + 1):
            if problem.isWall((x, y)):
                continue
            else:
                stateList.append((x, y))

    for time in range(maxTime):
        oneStateList = []
        for state in stateList:
            oneStateList.append(
                logic.PropSymbolExpr("P", state[0], state[1], time))
            legalActionList = problem.actions((state, foodGrid))
            illegalList = []
            for action in DirectionsList:
                if action in legalActionList:
                    nextState = problem.result((state, foodGrid), action)[0][0]
                    # state & action >> new state
                    nextLogic = (logic.PropSymbolExpr(
                        "P", state[0], state[1], time) & logic.PropSymbolExpr(
                            action, time)) >> logic.PropSymbolExpr(
                                'P', nextState[0], nextState[1], time + 1)
                    cnf.append(logic.to_cnf(nextLogic))
                else:
                    illegalList.append(action)
            for action in illegalList:
                # state >> not illegal action
                cnf.append(
                    logic.to_cnf(
                        logic.PropSymbolExpr("P", state[0], state[1], time) >>
                        ~logic.PropSymbolExpr(action, time)))

        # uses oneStateList, makes sure we are not in two places at once
        oneState = exactlyOne(oneStateList)
        cnf.append((oneState))

        # Exactly 1 move per turn
        Dir = []
        for direction in DirectionsList:
            Dir.append(logic.PropSymbolExpr(direction, time))
        oneMove = exactlyOne(Dir)
        cnf.append(logic.to_cnf(oneMove))

        # goal state (must hit each pellet once)
        foodAllEaten = []
        for food in foodPosList:
            foodOnce = []
            for alltime in range(time + 1):
                foodOnce.append(
                    logic.PropSymbolExpr('P', food[0], food[1], alltime))
            atLeastOnce = logic.associate('|', foodOnce)
            foodAllEaten.append(atLeastOnce)
        goalLogic = logic.associate('&', foodAllEaten)
        cnf.append(goalLogic)

        #Pacman and Ghost not in same place
        def ghostPositionfinder(ghoststart, time):
            ghostposition = ghoststart
            x = ghoststart[0]
            y = ghoststart[1]
            East = True
            for t in range(time):
                if East == True:
                    x += 1
                    if problem.isWall((x, y)):
                        x -= 2
                        East = False
                elif East == False:
                    x -= 1
                    if problem.isWall((x, y)):
                        x += 2
                        East = True
            return (x, y)
            #logic.PropSymbolExpr("G", ghostPos[0], ghostPos[1], 0)

        for ghostStartState in ghostStartStateList:
            ghostPos = ghostStartState.getPosition()
            ghostCurrentPos = ghostPositionfinder(ghostPos, time)
            cnf.append(
                logic.PropSymbolExpr("G", ghostCurrentPos[0],
                                     ghostCurrentPos[1], time))

        for pos in stateList:
            plsnodie = [logic.PropSymbolExpr("P", pos[0], pos[1], time)
                        ] + [logic.PropSymbolExpr("G", pos[0], pos[1], time)]
            cnf.append(atMostOne(plsnodie))
            plsnodie = [logic.PropSymbolExpr("P", pos[0], pos[1], time)] + [
                logic.PropSymbolExpr("G", pos[0], pos[1], time - 1)
            ]
            cnf.append(atMostOne(plsnodie))

        model = logic.pycoSAT(cnf)
        if model:
            path = extractActionSequence(model, DirectionsList)
            return path
        cnf.remove(goalLogic)

    print("you suck")
Ejemplo n.º 13
0
def foodLogicPlan(problem):
    """
    Given an instance of a FoodSearchProblem, return a list of actions that help Pacman
    eat all of the food.
    Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST}
    Note that STOP is not an available action.
    """
    "*** YOUR CODE HERE ***"
    cnf = []
    maxTime = 51
    n = Directions.NORTH
    s = Directions.SOUTH
    e = Directions.EAST
    w = Directions.WEST
    DirectionsList = [n, s, e, w]
    width = problem.getWidth() + 1
    height = problem.getHeight() + 1
    #Starting State
    swag = problem.getStartState()
    startState = swag[0]
    #Get positions of food
    foodGrid = swag[1]
    foodPosList = []
    for x in range(width + 1):
        for y in range(height + 1):
            if foodGrid[x][y]:
                foodPosList.append((x, y))

    pacmanStart = logic.PropSymbolExpr("P", startState[0], startState[1], 0)
    nonStartStates = []
    for x in range(1, width):
        for y in range(1, height):
            if (x, y) == (startState[0], startState[1]):
                continue
            else:
                nonStartStates.append(logic.PropSymbolExpr("P", x, y, 0))
            startLogic = logic.to_cnf(
                pacmanStart & ~(logic.associate('|', nonStartStates)))
    cnf.append(startLogic)

    stateList = []
    for x in range(width + 1):
        for y in range(height + 1):
            if problem.isWall((x, y)):
                continue
            else:
                stateList.append((x, y))

    for time in range(maxTime):
        #print time
        oneStateList = []
        for state in stateList:
            oneStateList.append(
                logic.PropSymbolExpr("P", state[0], state[1], time))
            legalActionList = problem.actions((state, foodGrid))
            illegalList = []
            for action in DirectionsList:
                if action in legalActionList:
                    nextState = problem.result((state, foodGrid), action)[0][0]
                    # state & action >> new state
                    nextLogic = (logic.PropSymbolExpr(
                        "P", state[0], state[1], time) & logic.PropSymbolExpr(
                            action, time)) >> logic.PropSymbolExpr(
                                'P', nextState[0], nextState[1], time + 1)
                    cnf.append(logic.to_cnf(nextLogic))
                else:
                    illegalList.append(action)
            for action in illegalList:
                # state >> not illegal action
                cnf.append(
                    logic.to_cnf(
                        logic.PropSymbolExpr("P", state[0], state[1], time) >>
                        ~logic.PropSymbolExpr(action, time)))

        # uses oneStateList, makes sure we are not in two places at once
        oneState = exactlyOne(oneStateList)
        cnf.append((oneState))

        # Exactly 1 move per turn
        Dir = []
        for direction in DirectionsList:
            Dir.append(logic.PropSymbolExpr(direction, time))
        oneMove = exactlyOne(Dir)
        cnf.append(logic.to_cnf(oneMove))

        # goal state (must hit each pellet once)
        foodAllEaten = []
        for food in foodPosList:
            foodOnce = []
            for alltime in range(time + 1):
                foodOnce.append(
                    logic.PropSymbolExpr('P', food[0], food[1], alltime))
            atLeastOnce = logic.associate('|', foodOnce)
            foodAllEaten.append(atLeastOnce)
        goalLogic = logic.associate('&', foodAllEaten)
        cnf.append(goalLogic)
        model = logic.pycoSAT(cnf)
        if model:
            path = extractActionSequence(model, DirectionsList)
            return path
        cnf.remove(goalLogic)
    print("you suck")
Ejemplo n.º 14
0
def positionLogicPlan(problem):
    """
    Given an instance of a PositionSearchProblem, return a list of actions that lead to the goal.
    Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST}
    Note that STOP is not an available action.
    """

    "*** YOUR CODE HERE ***"
    cnf = []
    maxTime = 51
    n = Directions.NORTH
    s = Directions.SOUTH
    e = Directions.EAST
    w = Directions.WEST
    DirectionsList = [n, s, e, w]
    width = problem.getWidth() + 1
    height = problem.getHeight() + 1
    #Starting State
    startState = problem.getStartState()
    pacmanStart = logic.PropSymbolExpr("P", startState[0], startState[1], 0)
    nonStartStates = []
    for x in range(1, width):
        for y in range(1, height):
            if (x, y) == (startState[0], startState[1]):
                continue
            else:
                nonStartStates.append(logic.PropSymbolExpr("P", x, y, 0))
            startLogic = logic.to_cnf(
                pacmanStart & ~(logic.associate('|', nonStartStates)))
    cnf.append(startLogic)

    goalState = problem.getGoalState()

    stateList = []
    for x in range(width + 1):
        for y in range(height + 1):
            if problem.isWall((x, y)):
                continue
            else:
                stateList.append((x, y))

    for time in range(maxTime):
        oneStateList = []
        for state in stateList:
            oneStateList.append(
                logic.PropSymbolExpr("P", state[0], state[1], time))
            legalActionList = problem.actions(state)
            illegalList = []
            for action in DirectionsList:
                if action in legalActionList:
                    nextState = problem.result(state, action)[0]
                    # state & action >> new state
                    nextLogic = (logic.PropSymbolExpr(
                        "P", state[0], state[1], time) & logic.PropSymbolExpr(
                            action, time)) >> logic.PropSymbolExpr(
                                'P', nextState[0], nextState[1], time + 1)
                    cnf.append(logic.to_cnf(nextLogic))
                else:
                    illegalList.append(action)
            for action in illegalList:
                # state >> not illegal action
                cnf.append(
                    logic.to_cnf(
                        logic.PropSymbolExpr('P', state[0], state[1], time) >>
                        ~logic.PropSymbolExpr(action, time)))

        # uses oneStateList, makes sure we are not in two places at once
        oneState = exactlyOne(oneStateList)
        cnf.append((oneState))

        # Exactly 1 move per turn
        Dir = []
        for direction in DirectionsList:
            Dir.append(logic.PropSymbolExpr(direction, time))
        oneMove = exactlyOne(Dir)
        cnf.append(logic.to_cnf(oneMove))

        # goal state
        cnf.append(logic.PropSymbolExpr("P", goalState[0], goalState[1], time))

        #print time

        model = logic.pycoSAT(cnf)
        if model:
            path = extractActionSequence(model, DirectionsList)
            return path

        cnf.remove(logic.PropSymbolExpr("P", goalState[0], goalState[1], time))
Ejemplo n.º 15
0
    def get_next_action(self, observation):
        # TODO : COMPLETE BY STUDENTS
        # get observation for the current state and return next action to apply (and None if no action is applicable)
        #self.space_kb.tell()
        cleared = False
        #print(self.state)
        for prev_tar in self.problem[3]:
            for tar in self.state[3]:
                if prev_tar[0] == tar[0]:
                    if len(prev_tar[1]) != len(tar[1]):
                        self.states=[]
                        self.prev_fit = None
                        cleared=True
        if cleared:
            print("CLEARED")
            self.problem=self.state
        # Take a ship and look for the closest target+calibration


        actions = self.actions(self.state)
        #print(actions)
        next_action = None

        next_target = None
        ship_missions=[]
        for ship in self.state[1]:

            for action in actions:
                if observation.get(ship[0]) != -1:
                    if observation.get(ship[0]) == 1:
                        pos_str = 'P' + str(ship[1])
                        self.space_kb.tell(~logic.expr(pos_str))

                    elif observation.get(ship[0])==0:
                        pos_str='P'+str(ship[1])
                        self.space_kb.tell(~logic.expr(pos_str))
                        pos_str='P'+str((ship[1][0]+1,ship[1][1],ship[1][2]))
                        self.space_kb.tell(~logic.expr(pos_str))
                        pos_str = 'P' + str((ship[1][0]-1, ship[1][1], ship[1][2]))
                        self.space_kb.tell(~logic.expr(pos_str))
                        pos_str = 'P' + str((ship[1][0], ship[1][1]+1, ship[1][2]))
                        self.space_kb.tell(~logic.expr(pos_str))
                        pos_str = 'P' + str((ship[1][0], ship[1][1]-1, ship[1][2]))
                        self.space_kb.tell(~logic.expr(pos_str))
                        pos_str = 'P' + str((ship[1][0], ship[1][1], ship[1][2]+1))
                        self.space_kb.tell(~logic.expr(pos_str))
                        pos_str = 'P' + str((ship[1][0], ship[1][1], ship[1][2]-1))
                        self.space_kb.tell(~logic.expr(pos_str))
                    if action[0] == "use" and action [1] == ship[0]:
                        self.state = self.result(self.state, action)
                        self.states.append(self.state)
                        return action
                    if action[0] == "calibrate" and action [1] == ship[0] and ship[2][1]==False:
                        self.state = self.result(self.state, action)
                        self.states.append(self.state)
                        return action
                    if ship[2][0] is None:
                        if action[0] == "turn_on" and action[1] == ship[0]:
                            need_for_weapon = False
                            for tar in self.state[3]:
                                if action[2] in tar[1]:
                                    need_for_weapon = True
                            if need_for_weapon:
                                self.state = self.result(self.state, action)
                                self.states.append(self.state)
                                return action

            fitness = -1
            tmp_min_fit=None
            if observation.get(ship[0]) != -1:
                ntarget = best_next_target(ship, self.state)
                if ntarget != ():
                    fitness = ntarget[0]+observation.get(ship[0])+1
                if tmp_min_fit is None:
                    tmp_min_fit = fitness
                    next_target = ntarget
                if 0 < fitness < tmp_min_fit:
                    tmp_min_fit = fitness
                    next_target = ntarget

            if next_target != ():
                ship_missions.append((next_target,ship))
        tmp_best = None
        for mission in ship_missions:
            if tmp_best is None:
                tmp_best = mission

            if 0<mission[0][0]<tmp_best[0][0]:
                tmp_best = mission
        '''if self.prev_fit is None:
            print (mission[0][0])
            self.prev_fit = mission[0][0]
        elif self.prev_fit<mission[0][0]:
            self.prev_fit=None
            self.state = self.result(self.state, self.move_back)
            return self.move_back
        else:
            self.prev_fit=mission[0][0]'''
        if mission[1][2][0] not in mission[0][1][1]:
            next_action = ("turn_on", mission[1][0], mission[0][2][0])
            self.state=self.result(self.state,next_action)

            return  next_action
        next_action = self.next_move_to_mission(mission, self.state)
        if next_action is None:
            return self.move_back
        allow=logic.dpll_satisfiable(logic.to_cnf(logic.associate('&',self.space_kb.clauses + [logic.expr('P'+str(next_action[3]))])))
        #print(allow)
        tmp_state = self.result(self.state, next_action)
        self.states.append(tmp_state)
        while allow != False:
            print('Achtung Laser')
            print(allow)
            next_action = self.next_move_to_mission(mission, self.state)
            tmp_state = self.result(self.state, next_action)
            self.states.append(tmp_state)
            if len(self.states)>6:
                self.states.clear()
            allow = logic.dpll_satisfiable(
                logic.to_cnf(logic.associate('&', self.space_kb.clauses + [logic.expr('P' + str(next_action[3]))])))
            #print(allow)
        self.state=tmp_state
        self.move_back = (next_action[0], next_action[1], next_action[3],next_action[2])
        return next_action