人工智能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

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,185评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,652评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,524评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,339评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,387评论 6 391
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,287评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,130评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,985评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,420评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,617评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,779评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,477评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,088评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,716评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,857评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,876评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,700评论 2 354

推荐阅读更多精彩内容