Advertisement
StefanTodorovski

(Python) AI: Snake (Змија)

Jun 12th, 2019
428
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 25.26 KB | None | 0 0
  1. import sys
  2. import math
  3. import random
  4. import bisect
  5. from sys import maxsize as infinity
  6.  
  7. """
  8. Defining a class for the problem structure that we will solve with a search.
  9. The Problem class is an abstract class from which we make inheritance to define the basic
  10. characteristics of every problem we want to solve
  11. """
  12.  
  13.  
  14. class Problem:
  15.     def __init__(self, initial, goal=None):
  16.         self.initial = initial
  17.         self.goal = goal
  18.  
  19.     def successor(self, state):
  20.         """Given a state, return a dictionary of {action : state} pairs reachable
  21.        from this state. If there are many successors, consider an iterator
  22.        that yields the successors one at a time, rather than building them
  23.        all at once.
  24.  
  25.        :param state: given state
  26.        :return:  dictionary of {action : state} pairs reachable
  27.                  from this state
  28.        :rtype: dict
  29.        """
  30.         raise NotImplementedError
  31.  
  32.     def actions(self, state):
  33.         """Given a state, return a list of all actions possible
  34.        from that state
  35.  
  36.        :param state: given state
  37.        :return: list of actions
  38.        :rtype: list
  39.        """
  40.         raise NotImplementedError
  41.  
  42.     def result(self, state, action):
  43.         """Given a state and action, return the resulting state
  44.  
  45.        :param state: given state
  46.        :param action: given action
  47.        :return: resulting state
  48.        """
  49.         raise NotImplementedError
  50.  
  51.     def goal_test(self, state):
  52.         """Return True if the state is a goal. The default method compares
  53.        the state to self.goal, as specified in the constructor. Implement
  54.        this method if checking against a single self.goal is not enough.
  55.  
  56.        :param state: given state
  57.        :return: is the given state a goal state
  58.        :rtype: bool
  59.        """
  60.         return state == self.goal
  61.  
  62.     def path_cost(self, c, state1, action, state2):
  63.         """Return the cost of a solution path that arrives at state2 from state1
  64.        via action, assuming cost c to get up to state1. If the problem is such
  65.        that the path doesn't matter, this function will only look at state2.
  66.        If the path does matter, it will consider c and maybe state1 and action.
  67.        The default method costs 1 for every step in the path.
  68.  
  69.        :param c: cost of the path to get up to state1
  70.        :param state1: given current state
  71.        :param action: action that needs to be done
  72.        :param state2: state to arrive to
  73.        :return: cost of the path after executing the action
  74.        :rtype: float
  75.        """
  76.         return c + 1
  77.  
  78.     def value(self):
  79.         """For optimization problems, each state has a value.
  80.        Hill-climbing and related algorithms try to maximize this value.
  81.  
  82.        :return: state value
  83.        :rtype: float
  84.        """
  85.         raise NotImplementedError
  86.  
  87.  
  88. """
  89. Definition of the class for node structure of the search.
  90. The class Node is not inherited
  91. """
  92.  
  93.  
  94. class Node:
  95.     def __init__(self, state, parent=None, action=None, path_cost=0):
  96.         """Create node from the search tree,  obtained from the parent by
  97.        taking the action
  98.  
  99.        :param state: current state
  100.        :param parent: parent state
  101.        :param action: action
  102.        :param path_cost: path cost
  103.        """
  104.         self.state = state
  105.         self.parent = parent
  106.         self.action = action
  107.         self.path_cost = path_cost
  108.         self.depth = 0  # search depth
  109.         if parent:
  110.             self.depth = parent.depth + 1
  111.  
  112.     def __repr__(self):
  113.         return "<Node %s>" % (self.state,)
  114.  
  115.     def __lt__(self, node):
  116.         return self.state < node.state
  117.  
  118.     def expand(self, problem):
  119.         """List the nodes reachable in one step from this node.
  120.  
  121.        :param problem: given problem
  122.        :return: list of available nodes in one step
  123.        :rtype: list(Node)
  124.        """
  125.  
  126.         return [self.child_node(problem, action)
  127.                 for action in problem.actions(self.state)]
  128.  
  129.     def child_node(self, problem, action):
  130.         """Return a child node from this node
  131.  
  132.        :param problem: given problem
  133.        :param action: given action
  134.        :return: available node  according to the given action
  135.        :rtype: Node
  136.        """
  137.         next_state = problem.result(self.state, action)
  138.         return Node(next_state, self, action,
  139.                     problem.path_cost(self.path_cost, self.state,
  140.                                       action, next_state))
  141.  
  142.     def solution(self):
  143.         """Return the sequence of actions to go from the root to this node.
  144.  
  145.        :return: sequence of actions
  146.        :rtype: list
  147.        """
  148.         return [node.action for node in self.path()[1:]]
  149.  
  150.     def solve(self):
  151.         """Return the sequence of states to go from the root to this node.
  152.  
  153.        :return: list of states
  154.        :rtype: list
  155.        """
  156.         return [node.state for node in self.path()[0:]]
  157.  
  158.     def path(self):
  159.         """Return a list of nodes forming the path from the root to this node.
  160.  
  161.        :return: list of states from the path
  162.        :rtype: list(Node)
  163.        """
  164.         x, result = self, []
  165.         while x:
  166.             result.append(x)
  167.             x = x.parent
  168.         result.reverse()
  169.         return result
  170.  
  171.     """We want the queue of nodes at breadth_first_search or
  172.    astar_search to not contain states-duplicates, so the nodes that
  173.    contain the same condition we treat as the same. [Problem: this can
  174.    not be desirable in other situations.]"""
  175.  
  176.     def __eq__(self, other):
  177.         return isinstance(other, Node) and self.state == other.state
  178.  
  179.     def __hash__(self):
  180.         return hash(self.state)
  181.  
  182.  
  183. """
  184. Definitions of helper structures for storing the list of generated, but not checked nodes
  185. """
  186.  
  187.  
  188. class Queue:
  189.     """Queue is an abstract class/interface. There are three types:
  190.        Stack(): Last In First Out Queue (stack).
  191.        FIFOQueue(): First In First Out Queue.
  192.        PriorityQueue(order, f): Queue in sorted order (default min-first).
  193.    """
  194.  
  195.     def __init__(self):
  196.         raise NotImplementedError
  197.  
  198.     def append(self, item):
  199.         """Adds the item into the queue
  200.  
  201.        :param item: given element
  202.        :return: None
  203.        """
  204.         raise NotImplementedError
  205.  
  206.     def extend(self, items):
  207.         """Adds the items into the queue
  208.  
  209.        :param items: given elements
  210.        :return: None
  211.        """
  212.         raise NotImplementedError
  213.  
  214.     def pop(self):
  215.         """Returns the first element of the queue
  216.  
  217.        :return: first element
  218.        """
  219.         raise NotImplementedError
  220.  
  221.     def __len__(self):
  222.         """Returns the number of elements in the queue
  223.  
  224.        :return: number of elements in the queue
  225.        :rtype: int
  226.        """
  227.         raise NotImplementedError
  228.  
  229.     def __contains__(self, item):
  230.         """Check if the queue contains the element item
  231.  
  232.        :param item: given element
  233.        :return: whether the queue contains the item
  234.        :rtype: bool
  235.        """
  236.         raise NotImplementedError
  237.  
  238.  
  239. class Stack(Queue):
  240.     """Last-In-First-Out Queue."""
  241.  
  242.     def __init__(self):
  243.         self.data = []
  244.  
  245.     def append(self, item):
  246.         self.data.append(item)
  247.  
  248.     def extend(self, items):
  249.         self.data.extend(items)
  250.  
  251.     def pop(self):
  252.         return self.data.pop()
  253.  
  254.     def __len__(self):
  255.         return len(self.data)
  256.  
  257.     def __contains__(self, item):
  258.         return item in self.data
  259.  
  260.  
  261. class FIFOQueue(Queue):
  262.     """First-In-First-Out Queue."""
  263.  
  264.     def __init__(self):
  265.         self.data = []
  266.  
  267.     def append(self, item):
  268.         self.data.append(item)
  269.  
  270.     def extend(self, items):
  271.         self.data.extend(items)
  272.  
  273.     def pop(self):
  274.         return self.data.pop(0)
  275.  
  276.     def __len__(self):
  277.         return len(self.data)
  278.  
  279.     def __contains__(self, item):
  280.         return item in self.data
  281.  
  282.  
  283. class PriorityQueue(Queue):
  284.     """A queue in which the minimum (or maximum) element is returned first
  285.     (as determined by f and order). This structure is used in
  286.     informed search"""
  287.  
  288.     def __init__(self, order=min, f=lambda x: x):
  289.         """
  290.        :param order: sorting function, if order is min, returns the element
  291.                      with minimal f (x); if the order is max, then returns the
  292.                      element with maximum f (x).
  293.        :param f: function f(x)
  294.        """
  295.         assert order in [min, max]
  296.         self.data = []
  297.         self.order = order
  298.         self.f = f
  299.  
  300.     def append(self, item):
  301.         bisect.insort_right(self.data, (self.f(item), item))
  302.  
  303.     def extend(self, items):
  304.         for item in items:
  305.             bisect.insort_right(self.data, (self.f(item), item))
  306.  
  307.     def pop(self):
  308.         if self.order == min:
  309.             return self.data.pop(0)[1]
  310.         return self.data.pop()[1]
  311.  
  312.     def __len__(self):
  313.         return len(self.data)
  314.  
  315.     def __contains__(self, item):
  316.         return any(item == pair[1] for pair in self.data)
  317.  
  318.     def __getitem__(self, key):
  319.         for _, item in self.data:
  320.             if item == key:
  321.                 return item
  322.  
  323.     def __delitem__(self, key):
  324.         for i, (value, item) in enumerate(self.data):
  325.             if item == key:
  326.                 self.data.pop(i)
  327.  
  328.  
  329. """
  330. Uninformed tree search.
  331. Within the tree we do not solve the loops.
  332. """
  333.  
  334.  
  335. def tree_search(problem, fringe):
  336.     """Search through the successors of a problem to find a goal.
  337.  
  338.    :param problem: given problem
  339.    :param fringe:  empty queue
  340.    :return: Node
  341.    """
  342.     fringe.append(Node(problem.initial))
  343.     while fringe:
  344.         node = fringe.pop()
  345.         print(node.state)
  346.         if problem.goal_test(node.state):
  347.             return node
  348.         fringe.extend(node.expand(problem))
  349.     return None
  350.  
  351.  
  352. def breadth_first_tree_search(problem):
  353.     """Search the shallowest nodes in the search tree first.
  354.  
  355.    :param problem: given problem
  356.    :return: Node
  357.    """
  358.     return tree_search(problem, FIFOQueue())
  359.  
  360.  
  361. def depth_first_tree_search(problem):
  362.     """Search the deepest nodes in the search tree first.
  363.  
  364.    :param problem: given problem
  365.    :return: Node
  366.    """
  367.     return tree_search(problem, Stack())
  368.  
  369.  
  370. """
  371. Uninformed graph search
  372. The main difference is that here we do not allow loops,
  373. i.e. repetition of states
  374. """
  375.  
  376.  
  377. def graph_search(problem, fringe):
  378.     """Search through the successors of a problem to find a goal.
  379. ? ?  If two paths reach a state, only use the best one.
  380.  
  381.    :param problem: given problem
  382.    :param fringe: empty queue
  383.    :return: Node
  384.    """
  385.     closed = set()
  386.     fringe.append(Node(problem.initial))
  387.     while fringe:
  388.         node = fringe.pop()
  389.         if problem.goal_test(node.state):
  390.             return node
  391.         if node.state not in closed:
  392.             closed.add(node.state)
  393.             fringe.extend(node.expand(problem))
  394.     return None
  395.  
  396.  
  397. def breadth_first_graph_search(problem):
  398.     """Search the shallowest nodes in the search tree first.
  399.  
  400.    :param problem: given problem
  401.    :return: Node
  402.    """
  403.     return graph_search(problem, FIFOQueue())
  404.  
  405.  
  406. def depth_first_graph_search(problem):
  407.     """Search the deepest nodes in the search tree first.
  408.  
  409.    :param problem: given problem
  410.    :return: Node
  411.    """
  412.     return graph_search(problem, Stack())
  413.  
  414.  
  415. def depth_limited_search(problem, limit=50):
  416.     def recursive_dls(node, problem, limit):
  417.         """Helper function for depth limited"""
  418.         cutoff_occurred = False
  419.         if problem.goal_test(node.state):
  420.             return node
  421.         elif node.depth == limit:
  422.             return 'cutoff'
  423.         else:
  424.             for successor in node.expand(problem):
  425.                 result = recursive_dls(successor, problem, limit)
  426.                 if result == 'cutoff':
  427.                     cutoff_occurred = True
  428.                 elif result is not None:
  429.                     return result
  430.         if cutoff_occurred:
  431.             return 'cutoff'
  432.         return None
  433.  
  434.     return recursive_dls(Node(problem.initial), problem, limit)
  435.  
  436.  
  437. def iterative_deepening_search(problem):
  438.     for depth in range(sys.maxsize):
  439.         result = depth_limited_search(problem, depth)
  440.         if result is not 'cutoff':
  441.             return result
  442.  
  443.  
  444. def uniform_cost_search(problem):
  445.     """Search the nodes in the search tree with lowest cost first."""
  446.     return graph_search(problem, PriorityQueue(min, lambda a: a.path_cost))
  447.  
  448.  
  449. """
  450. Informed graph search.
  451. """
  452.  
  453.  
  454. def memoize(fn, slot=None):
  455.     """ Store the calculated value for any arguments list. If a
  456.    slot is specified, store the result in that slot in the first
  457.    argument. If slot is false, store the results in a dictionary.
  458.  
  459.    :param fn: given function
  460.    :param slot: name of the attribute for saving the function results
  461.    :return: modified function for storing the results
  462.    """
  463.     if slot:
  464.         def memoized_fn(obj, *args):
  465.             if hasattr(obj, slot):
  466.                 return getattr(obj, slot)
  467.             else:
  468.                 val = fn(obj, *args)
  469.                 setattr(obj, slot, val)
  470.                 return val
  471.     else:
  472.         def memoized_fn(*args):
  473.             if args not in memoized_fn.cache:
  474.                 memoized_fn.cache[args] = fn(*args)
  475.             return memoized_fn.cache[args]
  476.  
  477.         memoized_fn.cache = {}
  478.     return memoized_fn
  479.  
  480.  
  481. def best_first_graph_search(problem, f):
  482.     """The idea of Best First Search is to use an evaluation function
  483.    to decide which adjacent is most promising and then explore.
  484.  
  485.    :param problem: given problem
  486.    :param f: given heuristic function
  487.    :return: Node or None
  488.    """
  489.     f = memoize(f, 'f')
  490.     node = Node(problem.initial)
  491.     if problem.goal_test(node.state):
  492.         return node
  493.     frontier = PriorityQueue(min, f)
  494.     frontier.append(node)
  495.     explored = set()
  496.     while frontier:
  497.         node = frontier.pop()
  498.         if problem.goal_test(node.state):
  499.             return node
  500.         explored.add(node.state)
  501.         for child in node.expand(problem):
  502.             if child.state not in explored and child not in frontier:
  503.                 frontier.append(child)
  504.             elif child in frontier:
  505.                 incumbent = frontier[child]
  506.                 if f(child) < f(incumbent):
  507.                     del frontier[incumbent]
  508.                     frontier.append(child)
  509.     return None
  510.  
  511.  
  512. def greedy_best_first_graph_search(problem, h=None):
  513.     """ Greedy best-first search is implemented with f(n) = h(n).
  514.  
  515.    :param problem: given problem
  516.    :param h: given heuristic function
  517.    :return: Node or None
  518.    """
  519.     h = memoize(h or problem.h, 'h')
  520.     return best_first_graph_search(problem, h)
  521.  
  522.  
  523. def astar_search(problem, h=None):
  524.     """ A* search is best-first graph search where f(n) = g(n) + h(n).
  525.  
  526.    :param problem: given problem
  527.    :param h: given heuristic function
  528.    :return: Node or None
  529.    """
  530.     h = memoize(h or problem.h, 'h')
  531.     return best_first_graph_search(problem, lambda n: n.path_cost + h(n))
  532.  
  533.  
  534. def recursive_best_first_search(problem, h=None):
  535.     """ Recursive best first search - limits recursion by
  536.    keeping track of the f-value of the best alternative
  537.    path from any ancestor node (one step look-ahead).
  538.  
  539.    :param problem: given problem
  540.    :param h: given heuristic function
  541.    :return: Node or None
  542.    """
  543.     h = memoize(h or problem.h, 'h')
  544.  
  545.     def RBFS(problem, node, flimit):
  546.         if problem.goal_test(node.state):
  547.             return node, 0  # (the second value is not important)
  548.         successors = node.expand(problem)
  549.         if len(successors) == 0:
  550.             return None, infinity
  551.         for s in successors:
  552.             s.f = max(s.path_cost + h(s), node.f)
  553.         while True:
  554.             # Sort them according to the lowest f value
  555.             successors.sort(key=lambda x: x.f)
  556.             best = successors[0]
  557.             if best.f > flimit:
  558.                 return None, best.f
  559.             if len(successors) > 1:
  560.                 alternative = successors[1].f
  561.             else:
  562.                 alternative = infinity
  563.             result, best.f = RBFS(problem, best, min(flimit, alternative))
  564.             if result is not None:
  565.                 return result, best.f
  566.  
  567.     node = Node(problem.initial)
  568.     node.f = h(node)
  569.     result, bestf = RBFS(problem, node, infinity)
  570.     return result
  571.  
  572.  
  573. """
  574. Finite graph search.
  575. """
  576.  
  577.  
  578. def distance(a, b):
  579.     """The distance between two (x, y) points."""
  580.     return math.hypot((a[0] - b[0]), (a[1] - b[1]))
  581.  
  582.  
  583. class Graph:
  584.     """A graph connects nodes (verticies) by edges (links).  Each edge can also
  585.    have a length associated with it.  The constructor call is something like:
  586.        g = Graph({'A': {'B': 1, 'C': 2})
  587.    this makes a graph with 3 nodes, A, B, and C, with an edge of length 1 from
  588.    A to B,  and an edge of length 2 from A to C.  You can also do:
  589.        g = Graph({'A': {'B': 1, 'C': 2}, directed=False)
  590.    This makes an undirected graph, so inverse links are also added. The graph
  591.    stays undirected; if you add more links with g.connect('B', 'C', 3), then
  592.    inverse link is also added.  You can use g.nodes() to get a list of nodes,
  593.    g.get('A') to get a dict of links out of A, and g.get('A', 'B') to get the
  594.    length of the link from A to B.  'Lengths' can actually be any object at
  595.    all, and nodes can be any hashable object."""
  596.  
  597.     def __init__(self, dictionary=None, directed=True):
  598.         self.dict = dictionary or {}
  599.         self.directed = directed
  600.         if not directed:
  601.             self.make_undirected()
  602.         else:
  603.             # add empty edges dictionary for those nodes that do not
  604.             # have edges and are not included in the dictionary as keys
  605.             nodes_no_edges = list({y for x in self.dict.values()
  606.                                    for y in x if y not in self.dict})
  607.             for node in nodes_no_edges:
  608.                 self.dict[node] = {}
  609.  
  610.     def make_undirected(self):
  611.         """Make a digraph into an undirected graph by adding symmetric edges."""
  612.         for a in list(self.dict.keys()):
  613.             for (b, dist) in self.dict[a].items():
  614.                 self.connect1(b, a, dist)
  615.  
  616.     def connect(self, node_a, node_b, distance_val=1):
  617.         """Add a link from node_a and node_b of given distance_val, and also add the inverse
  618.        link if the graph is undirected."""
  619.         self.connect1(node_a, node_b, distance_val)
  620.         if not self.directed:
  621.             self.connect1(node_b, node_a, distance_val)
  622.  
  623.     def connect1(self, node_a, node_b, distance_val):
  624.         """Add a link from node_a to node_b of given distance_val, in one direction only."""
  625.         self.dict.setdefault(node_a, {})[node_b] = distance_val
  626.  
  627.     def get(self, a, b=None):
  628.         """Return a link distance or a dict of {node: distance} entries.
  629.        .get(a,b) returns the distance or None;
  630.        .get(a) returns a dict of {node: distance} entries, possibly {}."""
  631.         links = self.dict.get(a)
  632.         if b is None:
  633.             return links
  634.         else:
  635.             return links.get(b)
  636.  
  637.     def nodes(self):
  638.         """Return a list of nodes in the graph."""
  639.         return list(self.dict.keys())
  640.  
  641.  
  642. def UndirectedGraph(dictionary=None):
  643.     """Build a Graph where every edge (including future ones) goes both ways."""
  644.     return Graph(dictionary=dictionary, directed=False)
  645.  
  646.  
  647. def RandomGraph(nodes=list(range(10)), min_links=2, width=400, height=300,
  648.                 curvature=lambda: random.uniform(1.1, 1.5)):
  649.     """Construct a random graph, with the specified nodes, and random links.
  650.    The nodes are laid out randomly on a (width x height) rectangle.
  651.    Then each node is connected to the min_links nearest neighbors.
  652.    Because inverse links are added, some nodes will have more connections.
  653.    The distance between nodes is the hypotenuse times curvature(),
  654.    where curvature() defaults to a random number between 1.1 and 1.5."""
  655.     g = UndirectedGraph()
  656.     g.locations = {}
  657.     # Build the cities
  658.     for node in nodes:
  659.         g.locations[node] = (random.randrange(width), random.randrange(height))
  660.     # Build roads from each city to at least min_links nearest neighbors.
  661.     for i in range(min_links):
  662.         for node in nodes:
  663.             if len(g.get(node)) < min_links:
  664.                 here = g.locations[node]
  665.  
  666.                 def distance_to_node(n):
  667.                     if n is node or g.get(node, n):
  668.                         return math.inf
  669.                     return distance(g.locations[n], here)
  670.  
  671.                 neighbor = nodes.index(min(nodes, key=distance_to_node))
  672.                 d = distance(g.locations[neighbor], here) * curvature()
  673.                 g.connect(node, neighbor, int(d))
  674.     return g
  675.  
  676.  
  677. class GraphProblem(Problem):
  678.     """The problem of searching a graph from one node to another."""
  679.  
  680.     def __init__(self, initial, goal, graph):
  681.         super().__init__(initial, goal)
  682.         self.graph = graph
  683.  
  684.     def actions(self, state):
  685.         """The actions at a graph node are just its neighbors."""
  686.         return list(self.graph.get(state).keys())
  687.  
  688.     def result(self, state, action):
  689.         """The result of going to a neighbor is just that neighbor."""
  690.         return action
  691.  
  692.     def path_cost(self, c, state1, action, state2):
  693.         return c + (self.graph.get(state1, state2) or math.inf)
  694.  
  695.     def h(self, node):
  696.         """h function is straight-line distance from a node's state to goal."""
  697.         locs = getattr(self.graph, 'locations', None)
  698.         if locs:
  699.             return int(distance(locs[node.state], locs[self.goal]))
  700.         else:
  701.             return math.inf
  702.  
  703.  
  704.  
  705. def new_pos_right(pos, dir):
  706.     x, y = pos
  707.  
  708.     if dir == "N":
  709.         pos = x, y+1
  710.         dir = "E"
  711.     elif dir == "S":
  712.         pos = x, y-1
  713.         dir = "W"
  714.     elif dir == "E":
  715.         pos = x+1, y
  716.         dir = "S"
  717.     elif dir == "W":
  718.         pos = x-1, y
  719.         dir = "N"
  720.  
  721.     return pos, dir
  722.  
  723.  
  724. def new_pos_left(pos, dir):
  725.     x, y = pos
  726.  
  727.     if dir == "N":
  728.         pos = x, y-1
  729.         dir = "W"
  730.     elif dir == "S":
  731.         pos = x, y+1
  732.         dir = "E"
  733.     elif dir == "E":
  734.         pos = x-1, y
  735.         dir = "N"
  736.     elif dir == "W":
  737.         pos = x+1, y
  738.         dir = "S"
  739.  
  740.     return pos, dir
  741.  
  742.  
  743. def new_pos_straight(pos, dir):
  744.     x, y = pos
  745.  
  746.     if dir == "N":
  747.         pos = x-1, y
  748.     elif dir == "S":
  749.         pos = x+1, y
  750.     elif dir == "E":
  751.         pos = x, y+1
  752.     elif dir == "W":
  753.         pos = x, y-1
  754.  
  755.     return pos, dir
  756.  
  757.  
  758. def is_valid(state):
  759.     x, y = state[0][0]
  760.     body = state[1]
  761.     red_apples = state[3]
  762.  
  763.     # Map bounds
  764.     if not (0 <= x <= 10 and 0 <= y <= 10):
  765.         return False
  766.  
  767.     # Body bound
  768.     if (x, y) in body:
  769.         return False
  770.  
  771.     # Red Apple
  772.     if (x, y) in red_apples:
  773.         return False
  774.  
  775.     return True
  776.  
  777.  
  778. class Snake(Problem):
  779.  
  780.     def __init__(self, initial):
  781.         super().__init__(initial)
  782.  
  783.     def goal_test(self, state):
  784.         return len(state[2]) == 0
  785.  
  786.     def successor(self, state):
  787.         succ = dict()
  788.  
  789.         pos = state[0][0]
  790.         dir = state[0][1]
  791.         red_apples = state[3]
  792.  
  793.         # Continue Straight
  794.         new_head = new_pos_straight(pos, dir)
  795.         new_body = state[1][0:]
  796.         new_green_apples = list(state[2])
  797.         if new_head[0] in new_green_apples:
  798.             new_green_apples.remove(new_head[0])
  799.         else:
  800.             new_body = new_body[0:-1]
  801.         new_state = new_head, new_body, tuple(new_green_apples), red_apples
  802.         if is_valid(new_state):
  803.             succ["ContinueStraight"] = new_state
  804.  
  805.         # Turn Left
  806.         new_head = new_pos_left(pos, dir)
  807.         new_body = state[1][0:]
  808.         new_green_apples = list(state[2])
  809.         if new_head[0] in new_green_apples:
  810.             new_green_apples.remove(new_head[0])
  811.         else:
  812.             new_body = new_body[0:-1]
  813.         new_state = new_head, new_body, tuple(new_green_apples), red_apples
  814.         if is_valid(new_state):
  815.             succ["TurnLeft"] = new_state
  816.  
  817.         # Turn Right
  818.         new_head = new_pos_right(pos, dir)
  819.         new_body = state[1][0:]
  820.         new_green_apples = list(state[2])
  821.         if new_head[0] in new_green_apples:
  822.             new_green_apples.remove(new_head[0])
  823.         else:
  824.             new_body = new_body[0:-1]
  825.         new_state = new_head, new_body, tuple(new_green_apples), red_apples
  826.         if is_valid(new_state):
  827.             succ["TurnRight"] = new_state
  828.  
  829.         return succ
  830.  
  831.     def actions(self, state):
  832.         return self.successor(state).keys()
  833.  
  834.     def result(self, state, action):
  835.         possible = self.successor(state)
  836.         return possible[action]
  837.  
  838.     def value(self):
  839.         pass
  840.  
  841.  
  842. if __name__ == '__main__':
  843.     n = int(input())
  844.     green_apples = [tuple(map(int, input().split(','))) for _ in range(n)]
  845.     m = int(input())
  846.     red_apples = [tuple(map(int, input().split(','))) for _ in range(m)]
  847.  
  848.     body = ((0, 0), (1, 0))
  849.     head_pos = (2, 0)
  850.     head_dir = "S" # N S W E (north, south, west, east)
  851.     head = (head_pos, head_dir)
  852.  
  853.     initial_state = head, body, tuple(green_apples), tuple(red_apples)
  854.     problem = Snake(initial_state)
  855.     answer = breadth_first_graph_search(problem)
  856.     print(answer.solution())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement