人工智能Pacman(二)(2018-05-24)

# 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 util

class SearchProblem:

? ? """

? ? This class outlines the structure of a search problem, but doesn't implement

? ? any 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 state

? ? ? ? Returns True if and only if the state is a valid goal state.

? ? ? ? """

? ? ? ? util.raiseNotDefined()

? ? def getSuccessors(self, state):

? ? ? ? """

? ? ? ? ? state: Search state

? ? ? ? For a given state, this should return a list of triples, (successor,

? ? ? ? action, stepCost), where 'successor' is a successor to the current

? ? ? ? state, 'action' is the action required to get there, and 'stepCost' is

? ? ? ? the incremental cost of expanding to that successor.

? ? ? ? """

? ? ? ? util.raiseNotDefined()

? ? def getCostOfActions(self, actions):

? ? ? ? """

? ? ? ? actions: A list of actions to take

? ? ? ? This 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, the

? ? sequence of moves will be incorrect, so only use this for tinyMaze.

? ? """

? ? from game import Directions

? ? s = Directions.SOUTH

? ? w = Directions.WEST

? ? return? [s, s, w, s, w, w, s, w]

def depthFirstSearch(problem):

? ? """

? ? Search the deepest nodes in the search tree first.

? ? Your search algorithm needs to return a list of actions that reaches the

? ? goal. Make sure to implement a graph search algorithm.

? ? To get started, you might want to try some of these simple commands to

? ? understand the search problem that is being passed in:

? ? print "Start:", problem.getStartState()

? ? print "Is the start a goal?", problem.isGoalState(problem.getStartState())

? ? print "Start's successors:", problem.getSuccessors(problem.getStartState())

? ? """

? ? "*** YOUR CODE HERE ***"

? ? from util import Stack

? ? from game import Directions

? ? fringe = Stack()

? ? closed = []

? ? fringe.push((problem.getStartState(), []))

? ? while not fringe.isEmpty():

? ? ? ? cur_node, actions = fringe.pop()

? ? ? ? if problem.isGoalState(cur_node):

? ? ? ? ? ? return actions

? ? ? ? if cur_node not in closed:

? ? ? ? ? ? expand = problem.getSuccessors(cur_node)

? ? ? ? ? ? closed.append(cur_node)

? ? ? ? ? ? for location, direction, cost in expand:

? ? ? ? ? ? ? ? if (location not in closed):

? ? ? ? ? ? ? ? ? ? fringe.push((location, actions + [direction]))

? ? util.raiseNotDefined()

def breadthFirstSearch(problem):

? ? """Search the shallowest nodes in the search tree first."""

? ? "*** YOUR CODE HERE ***"

? ? from util import Queue

? ? from game import Directions

? ? fringe = Queue()

? ? closed = []

? ? fringe.push((problem.getStartState(), []))

? ? while not fringe.isEmpty():

? ? ? ? cur_node, actions = fringe.pop()

? ? ? ? if problem.isGoalState(cur_node):

? ? ? ? ? ? return actions

? ? ? ? if cur_node not in closed:

? ? ? ? ? ? expand = problem.getSuccessors(cur_node)

? ? ? ? ? ? closed.append(cur_node)

? ? ? ? ? ? for location, direction, cost in expand:

? ? ? ? ? ? ? ? if (location not in closed):

? ? ? ? ? ? ? ? ? ? fringe.push((location, actions + [direction]))

? ? util.raiseNotDefined()

def uniformCostSearch(problem):

? ? """Search the node of least total cost first."""

? ? "*** YOUR CODE HERE ***"

? ? start_point = problem.getStartState()

? ? queue = util.PriorityQueueWithFunction(lambda x: x[2])

? ? queue.push((start_point,None,0))

? ? cost=0

? ? visited = []

? ? path = []

? ? parentSeq = {}

? ? parentSeq[(start_point,None,0)]=None

? ? while queue.isEmpty() == False:

? ? ? ? current_fullstate = queue.pop()

? ? ? ? #print current_fullstate

? ? ? ? if (problem.isGoalState(current_fullstate[0])):

? ? ? ? ? ? break

? ? ? ? else:

? ? ? ? ? ? current_state = current_fullstate[0]

? ? ? ? ? ? if current_state not in visited:

? ? ? ? ? ? ? ? visited.append(current_state)

? ? ? ? ? ? else:

? ? ? ? ? ? ? ? continue

? ? ? ? ? ? successors = problem.getSuccessors(current_state)

? ? ? ? ? ? for state in successors:

? ? ? ? ? ? ? ? cost= current_fullstate[2] + state[2];

? ? ? ? ? ? ? ? #print state,cost

? ? ? ? ? ? ? ? if state[0] not in visited:

? ? ? ? ? ? ? ? ? ? queue.push((state[0],state[1],cost))

? ? ? ? ? ? ? ? ? ? #parentSeq[state] = current_fullstate

? ? ? ? ? ? ? ? ? ? parentSeq[(state[0],state[1])] = current_fullstate

? ? child = current_fullstate

? ? while (child != None):

? ? ? ? path.append(child[1])

? ? ? ? if child[0] != start_point:

? ? ? ? ? ? child = parentSeq[(child[0],child[1])]

? ? ? ? else:

? ? ? ? ? ? child = None

? ? path.reverse()

? ? return path[1:]

? ? #util.raiseNotDefined()

def nullHeuristic(state, problem=None):

? ? """

? ? A heuristic function estimates the cost from the current state to the nearest

? ? goal in the provided SearchProblem.? This heuristic is trivial.

? ? """

? ? return 0

def aStarSearch(problem, heuristic=nullHeuristic):

? ? """Search the node that has the lowest combined cost and heuristic first."""

? ? "*** YOUR CODE HERE ***"

? ? from sets import Set

? ? fringe = util.PriorityQueue()

? ? actions = []

? ? fringe.push((problem.getStartState(),actions),0)

? ? visited = []

? ? tmpActions = []

? ? while fringe:

? ? ? ? currState,actions = fringe.pop()

? ? ? ? if problem.isGoalState(currState):

? ? ? ? ? ? break

? ? ? ? if currState not in visited:

? ? ? ? ? ? visited.append(currState)

? ? ? ? ? ? successors = problem.getSuccessors(currState)

? ? ? ? ? ? for successor, action, cost in successors:

? ? ? ? ? ? ? ? tempActions = actions + [action]

? ? ? ? ? ? ? ? nextCost = problem.getCostOfActions(tempActions) + heuristic(successor,problem)

? ? ? ? ? ? ? ? if successor not in visited:

? ? ? ? ? ? ? ? ? ? fringe.push((successor,tempActions),nextCost)

? ? return actions

? ? #util.raiseNotDefined()

# Abbreviations

bfs = breadthFirstSearch

dfs = depthFirstSearch

astar = aStarSearch

ucs = uniformCostSearch

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末克伊,一起剝皮案震驚了整個(gè)濱河市钩乍,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌缺脉,老刑警劉巖溉跃,帶你破解...
    沈念sama閱讀 217,509評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件赴魁,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)烂叔,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)固歪,“玉大人蒜鸡,你說(shuō)我怎么就攤上這事±紊眩” “怎么了逢防?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,875評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)蒲讯。 經(jīng)常有香客問(wèn)我忘朝,道長(zhǎng),這世上最難降的妖魔是什么判帮? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,441評(píng)論 1 293
  • 正文 為了忘掉前任局嘁,我火速辦了婚禮溉箕,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘悦昵。我一直安慰自己肴茄,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,488評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布但指。 她就那樣靜靜地躺著寡痰,像睡著了一般。 火紅的嫁衣襯著肌膚如雪棋凳。 梳的紋絲不亂的頭發(fā)上氓癌,一...
    開(kāi)封第一講書(shū)人閱讀 51,365評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音贫橙,去河邊找鬼贪婉。 笑死,一個(gè)胖子當(dāng)著我的面吹牛卢肃,可吹牛的內(nèi)容都是我干的疲迂。 我是一名探鬼主播,決...
    沈念sama閱讀 40,190評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼莫湘,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼尤蒿!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起幅垮,我...
    開(kāi)封第一講書(shū)人閱讀 39,062評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎忙芒,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體呵萨,經(jīng)...
    沈念sama閱讀 45,500評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,706評(píng)論 3 335
  • 正文 我和宋清朗相戀三年潮峦,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了囱皿。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,834評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡嘱腥,死狀恐怖拘悦,靈堂內(nèi)的尸體忽然破棺而出齿兔,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 35,559評(píng)論 5 345
  • 正文 年R本政府宣布愧驱,位于F島的核電站慰技,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏吻商。R本人自食惡果不足惜糟红,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,167評(píng)論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望盆偿。 院中可真熱鬧,春花似錦捎稚、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,779評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至涵亏,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間气筋,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,912評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工矛纹, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留光稼,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,958評(píng)論 2 370
  • 正文 我出身青樓艾君,卻偏偏與公主長(zhǎng)得像肄方,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子权她,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,779評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容