修改实验一,通过自动打分程序

master
huangjielun 2 years ago
parent 9418256a0b
commit 831eed19c4

@ -87,69 +87,85 @@ def depthFirstSearch(problem):
print "Start's successors:", problem.getSuccessors(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState())
""" """
"*** YOUR CODE HERE ***" "*** YOUR CODE HERE ***"
# start state visited_node = []
startState = problem.getStartState() myStack= util.Stack()
# have exit actions = []
exitState = [] s = problem.getStartState()
#use stack to dfs if problem.isGoalState(s):
States = util.Stack() return actions
States.push((startState,[])) myStack.push((s, actions))
#repeat a circle to confirm if it is successful while not myStack.isEmpty():
while (not States.isEmpty()) and (not problem.isGoalState(startState)): state = myStack.pop()
State,Actions = States.pop() if state[0] in visited_node:
if State not in exitState: continue
exitState.append(State) visited_node.append(state[0])
Successor = problem.getSuccessors(State) actions = state[1]
for Node in Successor: if (problem.isGoalState(state[0])):
Coordinates = Node[0] return actions
Direction = Node[1] for successor in problem.getSuccessors(state[0]):
if not Coordinates in exitState: child_state = successor[0]
States.push((Coordinates,Actions + [Direction])) action = successor[1]
startState = Coordinates sub_action = list(actions)
return Actions + [Direction] if not child_state in visited_node:
sub_action.append(action)
myStack.push((child_state, sub_action))
return actions
util.raiseNotDefined() util.raiseNotDefined()
def breadthFirstSearch(problem): def breadthFirstSearch(problem):
"""Search the shallowest nodes in the search tree first.""" """Search the shallowest nodes in the search tree first."""
"*** YOUR CODE HERE ***" "*** YOUR CODE HERE ***"
startState = problem.getStartState() visited_node = []
exitState = [] myQueue = util.Queue()
States = util.Queue() actions = []
States.push((startState,[])) s = problem.getStartState()
while (not States.isEmpty()) and (not problem.isGoalState(startState)): if problem.isGoalState(s):
State, Actions = States.pop() return actions
if State not in exitState: myQueue.push((s, actions))
Successor = problem.getSuccessors(State) while not myQueue.isEmpty():
exitState.append(State) state = myQueue.pop()
for Node in Successor: if state[0] in visited_node:
Coordinates = Node[0] continue
Direction = Node[1] visited_node.append(state[0])
if Coordinates not in exitState: actions = state[1]
States.push((Coordinates,Actions+[Direction])) if (problem.isGoalState(state[0])):
startState = Coordinates return actions
return Actions + [Direction] for successor in problem.getSuccessors(state[0]):
child_state = successor[0]
action = successor[1]
sub_action = list(actions)
if not child_state in visited_node:
sub_action.append(action)
myQueue.push((child_state, sub_action))
return actions
util.raiseNotDefined() util.raiseNotDefined()
def uniformCostSearch(problem): def uniformCostSearch(problem):
"""Search the node of least total cost first.""" """Search the node of least total cost first."""
"*** YOUR CODE HERE ***" "*** YOUR CODE HERE ***"
startState = problem.getStartState() visited_node = []
exitState = [] mypriorityQueue = util.PriorityQueue()
States = util.PriorityQueue() actions = []
States.push((startState, []),0) s = problem.getStartState()
while (not States.isEmpty()) and (not problem.isGoalState(startState)): if problem.isGoalState(s):
State, Actions = States.pop() return actions
if State not in exitState: mypriorityQueue.push((s, actions), 0)
Successor = problem.getSuccessors(State) while not mypriorityQueue.isEmpty():
exitState.append(State) state = mypriorityQueue.pop()
for Node in Successor: if state[0] in visited_node:
Coordinates = Node[0] continue
Direction = Node[1] visited_node.append(state[0])
if Coordinates not in exitState: actions = state[1]
newAction = Actions + [Direction] if (problem.isGoalState(state[0])):
States.push((Coordinates, newAction),problem.getCostOfActions(newAction)) return actions
startState = Coordinates for successor in problem.getSuccessors(state[0]):
return Actions + [Direction] child_state = successor[0]
action = successor[1]
sub_action = list(actions)
if not child_state in visited_node:
sub_action.append(action)
mypriorityQueue.push((child_state, sub_action), problem.getCostOfActions(sub_action))
return actions
util.raiseNotDefined() util.raiseNotDefined()
def nullHeuristic(state, problem=None): def nullHeuristic(state, problem=None):
@ -162,25 +178,29 @@ def nullHeuristic(state, problem=None):
def aStarSearch(problem, heuristic=nullHeuristic): def aStarSearch(problem, heuristic=nullHeuristic):
"""Search the node that has the lowest combined cost and heuristic first.""" """Search the node that has the lowest combined cost and heuristic first."""
"*** YOUR CODE HERE ***" "*** YOUR CODE HERE ***"
startState = problem.getStartState() visited_node = []
exitState = [] mypriorityQueue = util.PriorityQueue()
States = util.PriorityQueue() actions = []
h_n = heuristic(startState,problem) s = problem.getStartState()
States.push((startState, []), h_n) if problem.isGoalState(s):
while (not States.isEmpty()) and (not problem.isGoalState(startState)): return actions
State, Actions = States.pop() mypriorityQueue.push((s, actions), 0)
if State not in exitState: while not mypriorityQueue.isEmpty():
Successor = problem.getSuccessors(State) state = mypriorityQueue.pop()
exitState.append(State) if state[0] in visited_node:
for Node in Successor: continue
Coordinates = Node[0] visited_node.append(state[0])
Direction = Node[1] actions = state[1]
if Coordinates not in exitState: if (problem.isGoalState(state[0])):
newAction = Actions + [Direction] return actions
newCost = problem.getCostOfActions(newAction) + heuristic(Coordinates,problem) for successor in problem.getSuccessors(state[0]):
States.push((Coordinates, newAction), newCost) child_state = successor[0]
startState = Coordinates action = successor[1]
return Actions + [Direction] sub_action = list(actions)
if not child_state in visited_node:
sub_action.append(action)
mypriorityQueue.push((child_state, sub_action),heuristic(child_state, problem) + problem.getCostOfActions(sub_action))
return actions
util.raiseNotDefined() util.raiseNotDefined()

Binary file not shown.

@ -297,8 +297,7 @@ class CornersProblem(search.SearchProblem):
space) space)
""" """
"*** YOUR CODE HERE ***" "*** YOUR CODE HERE ***"
allCorners = (False,False,False,False) startState = (self.startingPosition,[])
startState = (self.startingPosition,allCorners)
return startState return startState
util.raiseNotDefined() util.raiseNotDefined()
@ -307,8 +306,14 @@ class CornersProblem(search.SearchProblem):
Returns whether this search state is a goal state of the problem. Returns whether this search state is a goal state of the problem.
""" """
"*** YOUR CODE HERE ***" "*** YOUR CODE HERE ***"
Corners = state[1] result = state[1]
return Corners[0] and Corners[1] and Corners[2] and Corners[3] if state[0] in self.corners:
if state[0] not in result:
result.append(state[0])
if (len(result) == 4):
return True
else:
return False
util.raiseNotDefined() util.raiseNotDefined()
def getSuccessors(self, state): def getSuccessors(self, state):
@ -332,31 +337,16 @@ class CornersProblem(search.SearchProblem):
# hitsWall = self.walls[nextx][nexty] # hitsWall = self.walls[nextx][nexty]
"*** YOUR CODE HERE ***" "*** YOUR CODE HERE ***"
x,y = state[0] x, y = state[0]
Corners = state[1] dx, dy = Actions.directionToVector(action)
Corners_0 = Corners[0]
Corners_1 = Corners[1]
Corners_2 = Corners[2]
Corners_3 = Corners[3]
dx , dy = Actions.directionToVector(action)
nextx, nexty = int(x + dx), int(y + dy) nextx, nexty = int(x + dx), int(y + dy)
hitsWall = self.walls[nextx][nexty] visited = list(state[1])
newCorners = [] if not self.walls[nextx][nexty]:
newState = (nextx,nexty) nextState = (nextx, nexty)
if not hitsWall: cost = 1
if newState in self.corners: if nextState in self.corners and nextState not in visited:
if newState == (1,1): visited.append(nextState)
newCorners = [True,Corners_1,Corners_2,Corners_3] successors.append(((nextState, visited), action, cost))
elif newState == (1,self.top):
newCorners = [Corners_0,True,Corners_2,Corners_3]
elif newState == (self.right,1):
newCorners = [Corners_0,Corners_1,True,Corners_3]
elif newState == (self.right,self.top):
newCorners = [Corners_0,Corners_1,Corners_2,True]
successor =((newState,newCorners),action,1)
else:
successor = ((newState,Corners),action,1)
successors.append(successor)
self._expanded += 1 # DO NOT CHANGE self._expanded += 1 # DO NOT CHANGE
return successors return successors
@ -391,37 +381,28 @@ def cornersHeuristic(state, problem):
walls = problem.walls # These are the walls of the maze, as a Grid (game.py) walls = problem.walls # These are the walls of the maze, as a Grid (game.py)
"*** YOUR CODE HERE ***" "*** YOUR CODE HERE ***"
currentPosition = state[0] visited = state[1]
stateCorners = state[1] now_state = state[0]
top = walls.height - 2 Heuristic = 0
right = walls.width - 2 last = []
Node = [] if (problem.isGoalState(state)):
return 0
for i in corners: for i in corners:
if i == (1,1): if i not in visited:
if not stateCorners[0]: last.append(i)
Node.append(i) pos = now_state
elif i == (1,top): cost = 999999
if not stateCorners[1]: while len(last) != 0:
Node.append(i) for i in last:
elif i == (right,top): if cost > (abs(pos[0] - i[0]) + abs(pos[1] - i[1])):
if not stateCorners[2]: min_con = i
Node.append(i) cost = (abs(pos[0] - i[0]) + abs(pos[1] - i[1]))
elif i == (right,1): Heuristic += cost
if not stateCorners[3]: pos = min_con
Node.append(i) cost = 999999
cost = 0 last.remove(min_con)
position = currentPosition return Heuristic
while len(Node) > 0:
distArr = []
for i in range(0,len(Node)):
dist = util.manhattanDistance(position,Node[i])
distArr.append(dist)
miniDist = min(distArr)
cost += miniDist
miniDist_I = distArr.index(miniDist)
position = Node[miniDist_I]
del Node[miniDist_I]
return cost # Default to trivial solution
class AStarCornersAgent(SearchAgent): class AStarCornersAgent(SearchAgent):
"A SearchAgent for FoodSearchProblem using A* and your foodHeuristic" "A SearchAgent for FoodSearchProblem using A* and your foodHeuristic"
@ -515,32 +496,30 @@ def foodHeuristic(state, problem):
""" """
position, foodGrid = state position, foodGrid = state
"*** YOUR CODE HERE ***" "*** YOUR CODE HERE ***"
hvalue = 0 lsFoodGrid = foodGrid.asList()
foodAvailable = [] last = list(lsFoodGrid)
totalDistance = 0 Heuristic = 0
for i in range(0,foodGrid.width): cost = 0
for j in range(0,foodGrid.height): max_con = position
if foodGrid[i][j] == True: for i in last:
foodLocation = (i,j) if cost < (abs(position[0] - i[0]) + abs(position[1] - i[1])):
foodAvailable.append(foodLocation) max_con = i
if len(foodAvailable) == 0: cost = (abs(position[0] - i[0]) + abs(position[1] - i[1]))
return 0 Heuristic = cost
maxDistance = ((0,0),(0,0),0) diff = position[0] - max_con[0]
for currentFood in foodAvailable: count = 0
for selectFood in foodAvailable: for i in last:
if currentFood == selectFood: if diff > 0:
pass if position[0] < i[0]:
else: count += 1
distance = util.manhattanDistance(currentFood,selectFood) if diff < 0:
if maxDistance[2] < distance: if position[0] > i[0]:
maxDistance = (currentFood,selectFood,distance) count += 1
if maxDistance[0] == (0,0) and maxDistance[1] == (0,0): if diff == 0:
hvalue = util.manhattanDistance(position,foodAvailable[0]) if position[0] != i[0]:
else: count += 1
dis_1 = util.manhattanDistance(position,maxDistance[0]) return Heuristic + count
dis_2 = util.manhattanDistance(position,maxDistance[1])
hvalue = min(dis_1,dis_2) + maxDistance[2]
return hvalue
class ClosestDotSearchAgent(SearchAgent): class ClosestDotSearchAgent(SearchAgent):
"Search for all food using a sequence of searches" "Search for all food using a sequence of searches"

Binary file not shown.
Loading…
Cancel
Save