当前位置: 首页 > news >正文

Pacman-search

文档

代码及文档:通过网盘分享的文件:code
链接: https://pan.baidu.com/s/1Rgo9ynnEqjZsSP2-6TyS8Q?pwd=n99p 提取码: n99p
在这里插入图片描述
在这里插入图片描述


补充核心代码

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述


核心代码内容:

search.py

# search.py
# ---------
# Licensing Information:  You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
# 
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu)."""
In search.py, you will implement generic search algorithms which are called by
Pacman agents (in searchAgents.py).
"""import utilclass SearchProblem:"""This class outlines the structure of a search problem, but doesn't implementany of the methods (in object-oriented terminology: an abstract class).You do not need to change anything in this class, ever."""def getStartState(self):"""Returns the start state for the search problem."""util.raiseNotDefined()def isGoalState(self, state):"""state: Search stateReturns True if and only if the state is a valid goal state."""util.raiseNotDefined()def getSuccessors(self, state):"""state: Search stateFor a given state, this should return a list of triples, (successor,action, stepCost), where 'successor' is a successor to the currentstate, 'action' is the action required to get there, and 'stepCost' isthe incremental cost of expanding to that successor."""util.raiseNotDefined()def getCostOfActions(self, actions):"""actions: A list of actions to takeThis method returns the total cost of a particular sequence of actions.The sequence must be composed of legal moves."""util.raiseNotDefined()def tinyMazeSearch(problem):"""Returns a sequence of moves that solves tinyMaze.  For any other maze, thesequence of moves will be incorrect, so only use this for tinyMaze."""from game import Directionss = Directions.SOUTHw = Directions.WESTreturn [s, s, w, s, w, w, s, w]def depthFirstSearch(problem):"""Search the deepest nodes in the search tree first."""from util import Stackstack = Stack()start_state = problem.getStartState()visited = set()stack.push((start_state, []))  # (current_state, path_to_state)while not stack.isEmpty():state, actions = stack.pop()if problem.isGoalState(state):return actionsif state not in visited:visited.add(state)for successor, action, _ in problem.getSuccessors(state):if successor not in visited:stack.push((successor, actions + [action]))return []  # If no path to the goaldef breadthFirstSearch(problem):"""Search the shallowest nodes in the search tree first."""from util import Queuequeue = Queue()start_state = problem.getStartState()visited = set()queue.push((start_state, []))  # (current_state, path_to_state)while not queue.isEmpty():state, actions = queue.pop()if problem.isGoalState(state):return actionsif state not in visited:visited.add(state)for successor, action, _ in problem.getSuccessors(state):if successor not in visited:queue.push((successor, actions + [action]))return []  # If no path to the goaldef uniformCostSearch(problem):"""Search the node of least total cost first."""from util import PriorityQueuepriority_queue = PriorityQueue()start_state = problem.getStartState()visited = set()priority_queue.push((start_state, []), 0)  # (current_state, path_to_state)while not priority_queue.isEmpty():state, actions = priority_queue.pop()if problem.isGoalState(state):return actionsif state not in visited:visited.add(state)for successor, action, cost in problem.getSuccessors(state):if successor not in visited:new_cost = problem.getCostOfActions(actions + [action])priority_queue.push((successor, actions + [action]), new_cost)return []  # If no path to the goaldef nullHeuristic(state, problem=None):"""A heuristic function estimates the cost from the current state to the nearestgoal in the provided SearchProblem. This heuristic is trivial."""return 0def aStarSearch(problem, heuristic=nullHeuristic):"""Search the node that has the lowest combined cost and heuristic first."""from util import PriorityQueuepriority_queue = PriorityQueue()start_state = problem.getStartState()visited = set()priority_queue.push((start_state, []), heuristic(start_state, problem))  # Initial priority is just heuristicwhile not priority_queue.isEmpty():state, actions = priority_queue.pop()if problem.isGoalState(state):return actionsif state not in visited:visited.add(state)for successor, action, cost in problem.getSuccessors(state):if successor not in visited:new_cost = problem.getCostOfActions(actions + [action])priority_queue.push((successor, actions + [action]),new_cost + heuristic(successor, problem))  # f(n) = g(n) + h(n)return []  # If no path to the goal# Abbreviations for convenience
bfs = breadthFirstSearch
dfs = depthFirstSearch
astar = aStarSearch
ucs = uniformCostSearch

searchAgent.py

# searchAgents.py
# ---------------
# Licensing Information:  You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
# 
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu)."""
This file contains all of the agents that can be selected to control Pacman.  To
select an agent, use the '-p' option when running pacman.py.  Arguments can be
passed to your agent using '-a'.  For example, to load a SearchAgent that uses
depth first search (dfs), run the following command:> python pacman.py -p SearchAgent -a fn=depthFirstSearchCommands to invoke other search strategies can be found in the project
description.Please only change the parts of the file you are asked to.  Look for the lines
that say"*** YOUR CODE HERE ***"The parts you fill in start about 3/4 of the way down.  Follow the project
description for details.Good luck and happy searching!
"""from game import Directions
from game import Agent
from game import Actions
import util
import time
import searchclass GoWestAgent(Agent):"An agent that goes West until it can't."def getAction(self, state):"The agent receives a GameState (defined in pacman.py)."if Directions.WEST in state.getLegalPacmanActions():return Directions.WESTelse:return Directions.STOP#######################################################
# This portion is written for you, but will only work #
#       after you fill in parts of search.py          #
#######################################################class SearchAgent(Agent):"""This very general search agent finds a path using a supplied searchalgorithm for a supplied search problem, then returns actions to follow thatpath.As a default, this agent runs DFS on a PositionSearchProblem to findlocation (1,1)Options for fn include:depthFirstSearch or dfsbreadthFirstSearch or bfsNote: You should NOT change any code in SearchAgent"""def __init__(self, fn='depthFirstSearch', prob='PositionSearchProblem', heuristic='nullHeuristic'):# Warning: some advanced Python magic is employed below to find the right functions and problems# Get the search function from the name and heuristicif fn not in dir(search):raise AttributeError(fn + ' is not a search function in search.py.')func = getattr(search, fn)if 'heuristic' not in func.__code__.co_varnames:print('[SearchAgent] using function ' + fn)self.searchFunction = funcelse:if heuristic in globals().keys():heur = globals()[heuristic]elif heuristic in dir(search):heur = getattr(search, heuristic)else:raise AttributeError(heuristic + ' is not a function in searchAgents.py or search.py.')print('[SearchAgent] using function %s and heuristic %s' % (fn, heuristic))# Note: this bit of Python trickery combines the search algorithm and the heuristicself.searchFunction = lambda x: func(x, heuristic=heur)# Get the search problem type from the nameif prob not in globals().keys() or not prob.endswith('Problem'):raise AttributeError(prob + ' is not a search problem type in SearchAgents.py.')self.searchType = globals()[prob]print('[SearchAgent] using problem type ' + prob)def registerInitialState(self, state):"""This is the first time that the agent sees the layout of the gameboard. Here, we choose a path to the goal. In this phase, the agentshould compute the path to the goal and store it in a local variable.All of the work is done in this method!state: a GameState object (pacman.py)"""if self.searchFunction == None: raise Exception("No search function provided for SearchAgent")starttime = time.time()problem = self.searchType(state) # Makes a new search problemself.actions  = self.searchFunction(problem) # Find a pathtotalCost = problem.getCostOfActions(self.actions)print('Path found with total cost of %d in %.1f seconds' % (totalCost, time.time() - starttime))if '_expanded' in dir(problem): print('Search nodes expanded: %d' % problem._expanded)def getAction(self, state):"""Returns the next action in the path chosen earlier (inregisterInitialState).  Return Directions.STOP if there is no furtheraction to take.state: a GameState object (pacman.py)"""if 'actionIndex' not in dir(self): self.actionIndex = 0i = self.actionIndexself.actionIndex += 1if i < len(self.actions):return self.actions[i]else:return Directions.STOPclass PositionSearchProblem(search.SearchProblem):"""A search problem defines the state space, start state, goal test, successorfunction and cost function.  This search problem can be used to find pathsto a particular point on the pacman board.The state space consists of (x,y) positions in a pacman game.Note: this search problem is fully specified; you should NOT change it."""def __init__(self, gameState, costFn = lambda x: 1, goal=(1,1), start=None, warn=True, visualize=True):"""Stores the start and goal.gameState: A GameState object (pacman.py)costFn: A function from a search state (tuple) to a non-negative numbergoal: A position in the gameState"""self.walls = gameState.getWalls()self.startState = gameState.getPacmanPosition()if start != None: self.startState = startself.goal = goalself.costFn = costFnself.visualize = visualizeif warn and (gameState.getNumFood() != 1 or not gameState.hasFood(*goal)):print('Warning: this does not look like a regular search maze')# For display purposesself._visited, self._visitedlist, self._expanded = {}, [], 0 # DO NOT CHANGEdef getStartState(self):return self.startStatedef isGoalState(self, state):isGoal = state == self.goal# For display purposes onlyif isGoal and self.visualize:self._visitedlist.append(state)import __main__if '_display' in dir(__main__):if 'drawExpandedCells' in dir(__main__._display): #@UndefinedVariable__main__._display.drawExpandedCells(self._visitedlist) #@UndefinedVariablereturn isGoaldef getSuccessors(self, state):"""Returns successor states, the actions they require, and a cost of 1.As noted in search.py:For a given state, this should return a list of triples,(successor, action, stepCost), where 'successor' is asuccessor to the current state, 'action' is the actionrequired to get there, and 'stepCost' is the incrementalcost of expanding to that successor"""successors = []for action in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]:x,y = statedx, dy = Actions.directionToVector(action)nextx, nexty = int(x + dx), int(y + dy)if not self.walls[nextx][nexty]:nextState = (nextx, nexty)cost = self.costFn(nextState)successors.append( ( nextState, action, cost) )# Bookkeeping for display purposesself._expanded += 1 # DO NOT CHANGEif state not in self._visited:self._visited[state] = Trueself._visitedlist.append(state)return successorsdef getCostOfActions(self, actions):"""Returns the cost of a particular sequence of actions. If those actionsinclude an illegal move, return 999999."""if actions == None: return 999999x,y= self.getStartState()cost = 0for action in actions:# Check figure out the next state and see whether its' legaldx, dy = Actions.directionToVector(action)x, y = int(x + dx), int(y + dy)if self.walls[x][y]: return 999999cost += self.costFn((x,y))return costclass StayEastSearchAgent(SearchAgent):"""An agent for position search with a cost function that penalizes being inpositions on the West side of the board.The cost function for stepping into a position (x,y) is 1/2^x."""def __init__(self):self.searchFunction = search.uniformCostSearchcostFn = lambda pos: .5 ** pos[0]self.searchType = lambda state: PositionSearchProblem(state, costFn, (1, 1), None, False)class StayWestSearchAgent(SearchAgent):"""An agent for position search with a cost function that penalizes being inpositions on the East side of the board.The cost function for stepping into a position (x,y) is 2^x."""def __init__(self):self.searchFunction = search.uniformCostSearchcostFn = lambda pos: 2 ** pos[0]self.searchType = lambda state: PositionSearchProblem(state, costFn)def manhattanHeuristic(position, problem, info={}):"The Manhattan distance heuristic for a PositionSearchProblem"xy1 = positionxy2 = problem.goalreturn abs(xy1[0] - xy2[0]) + abs(xy1[1] - xy2[1])def euclideanHeuristic(position, problem, info={}):"The Euclidean distance heuristic for a PositionSearchProblem"xy1 = positionxy2 = problem.goalreturn ( (xy1[0] - xy2[0]) ** 2 + (xy1[1] - xy2[1]) ** 2 ) ** 0.5#####################################################
# This portion is incomplete.  Time to write code!  #
#####################################################class CornersProblem(search.SearchProblem):"""This search problem finds paths through all four corners of a layout.You must select a suitable state space and successor function."""def __init__(self, startingGameState):"""Stores the walls, pacman's starting position and corners."""self.walls = startingGameState.getWalls()self.startingPosition = startingGameState.getPacmanPosition()top, right = self.walls.height-2, self.walls.width-2self.corners = ((1, 1), (1, top), (right, 1), (right, top))for corner in self.corners:if not startingGameState.hasFood(*corner):print('Warning: no food in corner ' + str(corner))self._expanded = 0  # DO NOT CHANGE; Number of search nodes expanded# 如果有其它初始化内容,也可以在这里添加"*** YOUR CODE HERE ***"def getStartState(self):"""Returns the start state (in your state space, not the full Pacman state space)状态定义为 (position, visitedCorners) visitedCorners 为一个4元组,每个布尔值表示对应角落是否已被访问"""# 初始化visited状态,4个角落初始都未访问visited = [False] * 4# 如果起始位置恰好在某个角落,将该角落标记为已访问for i, corner in enumerate(self.corners):if self.startingPosition == corner:visited[i] = Truereturn (self.startingPosition, tuple(visited))def isGoalState(self, state):"""Returns whether this search state is a goal state of the problem.当四个角落都已访问时,即为目标状态。"""# state 为 (position, visited)return all(state[1])def getSuccessors(self, state):"""Returns successor states, the actions they require, and a cost of 1.对于当前状态 (position, visited),尝试所有四个方向的移动,若移动不撞墙,则更新位置;如果新的位置正好是某个角落,更新visited状态。"""successors = []from game import Directions, Actions  # 确保引入必要的方向和动作函数for action in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]:# 当前状态拆解currentPosition, visited = statex, y = currentPositiondx, dy = Actions.directionToVector(action)nextx, nexty = int(x + dx), int(y + dy)# 如果撞墙则跳过if self.walls[nextx][nexty]:continuenextPosition = (nextx, nexty)# 更新visited状态,注意要转换为可变类型再修改visited_list = list(visited)for i, corner in enumerate(self.corners):if nextPosition == corner:visited_list[i] = TruenewVisited = tuple(visited_list)successors.append(((nextPosition, newVisited), action, 1))self._expanded += 1  # DO NOT CHANGEreturn successorsdef getCostOfActions(self, actions):"""Returns the cost of a particular sequence of actions.如果动作中包含非法移动,返回一个很大的数字。这里已由系统实现,不需要修改。"""if actions == None: return 999999x, y = self.startingPositionfrom game import Actionsfor action in actions:dx, dy = Actions.directionToVector(action)x, y = int(x + dx), int(y + dy)if self.walls[x][y]: return 999999return len(actions)
def cornersHeuristic(state, problem):"""A heuristic for the CornersProblem.采用贪心策略:从当前位置开始,不断选择最近的未访问角落,累加它们之间的曼哈顿距离作为估计值。"""from util import manhattanDistanceposition, visited = state# 找出所有未访问的角落unvisited = []for i, corner in enumerate(problem.corners):if not visited[i]:unvisited.append(corner)heuristic = 0currentPos = position# 贪心地依次求出到最近角落的距离,并更新当前位置while unvisited:distances = [(manhattanDistance(currentPos, corner), corner) for corner in unvisited]d, nearest = min(distances)heuristic += dcurrentPos = nearestunvisited.remove(nearest)return heuristicclass AStarCornersAgent(SearchAgent):"A SearchAgent for FoodSearchProblem using A* and your foodHeuristic"def __init__(self):self.searchFunction = lambda prob: search.aStarSearch(prob, cornersHeuristic)self.searchType = CornersProblemclass FoodSearchProblem:"""A search problem associated with finding the a path that collects all of thefood (dots) in a Pacman game.A search state in this problem is a tuple ( pacmanPosition, foodGrid ) wherepacmanPosition: a tuple (x,y) of integers specifying Pacman's positionfoodGrid:       a Grid (see game.py) of either True or False, specifying remaining food"""def __init__(self, startingGameState):self.start = (startingGameState.getPacmanPosition(), startingGameState.getFood())self.walls = startingGameState.getWalls()self.startingGameState = startingGameStateself._expanded = 0 # DO NOT CHANGEself.heuristicInfo = {} # A dictionary for the heuristic to store informationdef getStartState(self):return self.startdef isGoalState(self, state):return state[1].count() == 0def getSuccessors(self, state):"Returns successor states, the actions they require, and a cost of 1."successors = []self._expanded += 1 # DO NOT CHANGEfor direction in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]:x,y = state[0]dx, dy = Actions.directionToVector(direction)nextx, nexty = int(x + dx), int(y + dy)if not self.walls[nextx][nexty]:nextFood = state[1].copy()nextFood[nextx][nexty] = Falsesuccessors.append( ( ((nextx, nexty), nextFood), direction, 1) )return successorsdef getCostOfActions(self, actions):"""Returns the cost of a particular sequence of actions.  If those actionsinclude an illegal move, return 999999"""x,y= self.getStartState()[0]cost = 0for action in actions:# figure out the next state and see whether it's legaldx, dy = Actions.directionToVector(action)x, y = int(x + dx), int(y + dy)if self.walls[x][y]:return 999999cost += 1return costclass AStarFoodSearchAgent(SearchAgent):"A SearchAgent for FoodSearchProblem using A* and your foodHeuristic"def __init__(self):self.searchFunction = lambda prob: search.aStarSearch(prob, foodHeuristic)self.searchType = FoodSearchProblemdef foodHeuristic(state, problem):"""这个启发式函数估计吃完所有食物至少需要走的步数。思路是:至少需要先走到离当前吃豆人最近的食物,然后还必须连接所有食物,这下界可以用所有食物之间的最大曼哈顿距离来近似。"""position, foodGrid = statefoodList = foodGrid.asList()# 没有食物时,启发值为0if not foodList:return 0# 定义曼哈顿距离函数def manhattan(a, b):return abs(a[0] - b[0]) + abs(a[1] - b[1])# 当前吃豆人与所有食物之间的最小曼哈顿距离min_distance = min(manhattan(position, food) for food in foodList)# 计算所有食物之间的最大曼哈顿距离max_pair_distance = 0for food1 in foodList:for food2 in foodList:# 两个不同食物之间的距离if food1 != food2:max_pair_distance = max(max_pair_distance, manhattan(food1, food2))# 启发值为最小距离加上食物间的最大距离return min_distance + max_pair_distanceclass ClosestDotSearchAgent(SearchAgent):"Search for all food using a sequence of searches"def registerInitialState(self, state):self.actions = []currentState = statewhile(currentState.getFood().count() > 0):nextPathSegment = self.findPathToClosestDot(currentState)self.actions += nextPathSegmentfor action in nextPathSegment:legal = currentState.getLegalActions()if action not in legal:t = (str(action), str(currentState))raise Exception('findPathToClosestDot returned an illegal move: %s!\n%s' % t)currentState = currentState.generateSuccessor(0, action)self.actionIndex = 0print('Path found with cost %d.' % len(self.actions))def findPathToClosestDot(self, gameState):"""Returns a path (a list of actions) to the closest dot, starting fromgameState."""# 利用 AnyFoodSearchProblem 构造问题,然后使用广度优先搜索求解problem = AnyFoodSearchProblem(gameState)return search.bfs(problem)  # 假设在 search.py 中实现了 bfs 函数class AnyFoodSearchProblem(PositionSearchProblem):"""A search problem for finding a path to any food.This search problem is just like the PositionSearchProblem, but has adifferent goal test, which you need to fill in below."""def __init__(self, gameState):"Stores information from the gameState.  You don't need to change this."# Store the food for later referenceself.food = gameState.getFood()# Store info for the PositionSearchProblem (no need to change this)self.walls = gameState.getWalls()self.startState = gameState.getPacmanPosition()self.costFn = lambda x: 1self._visited, self._visitedlist, self._expanded = {}, [], 0  # DO NOT CHANGEdef isGoalState(self, state):"""The state is Pacman's position. The goal is reached if there is food at this position."""x, y = statereturn self.food[x][y]def mazeDistance(point1, point2, gameState):"""Returns the maze distance between any two points, using the search functionsyou have already built. The gameState can be any game state -- Pacman'sposition in that state is ignored.Example usage: mazeDistance( (2,4), (5,6), gameState)This might be a useful helper function for your ApproximateSearchAgent."""x1, y1 = point1x2, y2 = point2walls = gameState.getWalls()assert not walls[x1][y1], 'point1 is a wall: ' + str(point1)assert not walls[x2][y2], 'point2 is a wall: ' + str(point2)prob = PositionSearchProblem(gameState, start=point1, goal=point2, warn=False, visualize=False)return len(search.bfs(prob))

相关文章:

  • 【RabbitMQ】保证消息不丢失
  • PaddleX的安装
  • “八股训练营”学习总结
  • C++STL(九) :bitset的介绍与使用
  • 特征工程四:数据特征提取TfidfVectorizer的使用
  • re题(48)BUUCTF-[网鼎杯 2020 青龙组]singal
  • 对日开发 秀丸文本编辑器 宏的基本使用
  • 计算属性 vs methods方法
  • Java大厂面试突击:从Spring Boot自动配置到Kafka分区策略实战解析
  • SVT-AV1源码分析-函数svt_aom_motion_estimation_kernel
  • linux:进程的替换
  • 深入解读:2025 数字化转型管理 参考架构
  • 【算法】回溯法
  • 杭电oj(1010、1015、1241)题解
  • 【沉浸式求职学习day27】
  • 【视频生成模型】通义万相Wan2.1模型本地部署和LoRA微调
  • Python----深度学习(基于DNN的吃鸡预测)
  • 动手学深度学习11.11. 学习率调度器-笔记练习(PyTorch)
  • arcpy列表函数的应用(4)
  • MySQL的锁(InnoDB)【学习笔记】
  • 美加征“对等关税”后,调研显示近半外贸企业将减少对美业务
  • 野猪穿过江苏电视台楼前广场,被抓捕后送往红山森林动物园
  • 商务部:入境消费增长潜力巨大,离境退税有助降低境外旅客购物成本
  • 葛兰西:“生活就是抵抗”
  • 大家聊中国式现代化|周冯琦:转角见美,让“绿意”触手可及
  • 海南旅文局通报游客入住酒店港币被调包:成立调查组赴陵水调查