Advertisement
HackerOK228

Untitled

Feb 17th, 2019
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.16 KB | None | 0 0
  1. from heapq import heappush, heappop
  2. from sys import maxsize
  3. import curses, random
  4. import re
  5. from serial import Serial
  6.  
  7. ser = Serial('/dev/ttyACM0',9600)
  8.  
  9.  
  10. DUNGEON = """
  11. #####################
  12. #     #     ###   # #
  13. #   #    #    # # # #
  14. # #    # #   ##   # #
  15. # ##  ##     ##  ## #
  16. ##     ### # ### ## #
  17. #  #          #     #
  18. ####    ### ##### ###
  19. #### ##      ###  ###
  20. ##   #####          #
  21. #####################
  22. """
  23.  
  24. F, H, NUM, G, POS, OPEN, VALID, PARENT = range(8)
  25.  
  26. HEIGHT, WIDTH = 11, 21
  27. MAX_LIMIT = HEIGHT * WIDTH
  28. LIMIT = MAX_LIMIT // 2
  29. DEBUG = False
  30. COLOR = True
  31.  
  32. def astar(start_pos, neighbors, goal, start_g, cost, heuristic, limit=maxsize):
  33.  
  34.    
  35.     nums = iter(range(maxsize))
  36.     start_h = heuristic(start_pos)
  37.     start = [start_g + start_h, start_h, next(nums), start_g, start_pos, True,
  38.              True, None]
  39.  
  40.    
  41.     nodes = {start_pos: start}
  42.     heap = [start]
  43.     best = start
  44.  
  45.     while heap:
  46.         current = heappop(heap)
  47.         current[OPEN] = False
  48.  
  49.         if goal(current[POS]):
  50.             best = current
  51.             break
  52.  
  53.         for neighbor_pos in neighbors(current[POS]):
  54.             neighbor_g = current[G] + cost(current[POS], neighbor_pos)
  55.             neighbor = nodes.get(neighbor_pos)
  56.             if neighbor is None:
  57.                 if len(nodes) >= limit:
  58.                     continue
  59.                    
  60.                 neighbor_h = heuristic(neighbor_pos)
  61.                 neighbor = [neighbor_g + neighbor_h, neighbor_h, next(nums),
  62.                             neighbor_g, neighbor_pos, True, True, current[POS]]
  63.                 nodes[neighbor_pos] = neighbor
  64.                 heappush(heap, neighbor)
  65.                 if neighbor_h < best[H]:
  66.                     best = neighbor
  67.  
  68.             elif neighbor_g < neighbor[G]:
  69.                 if neighbor[OPEN]:
  70.  
  71.                     neighbor[VALID] = False
  72.                     nodes[neighbor_pos] = neighbor = neighbor[:]
  73.                     neighbor[F] = neighbor_g + neighbor[H]
  74.                     neighbor[NUM] = next(nums)
  75.                     neighbor[G] = neighbor_g
  76.                     neighbor[VALID] = True
  77.                     neighbor[PARENT] = current[POS]
  78.                     heappush(heap, neighbor)
  79.                 else:
  80.                     neighbor[F] = neighbor_g + neighbor[H]
  81.                     neighbor[G] = neighbor_g
  82.                     neighbor[PARENT] = current[POS]
  83.                     neighbor[OPEN] = True
  84.                     heappush(heap, neighbor)
  85.  
  86.        
  87.         while heap and not heap[0][VALID]:
  88.             heappop(heap)    
  89.  
  90.     path = []
  91.     current = best
  92.     while current[PARENT] is not None:
  93.         path.append(current[POS])
  94.         current = nodes[current[PARENT]]
  95.     path.reverse()
  96.  
  97.     return path
  98.  
  99.  
  100. class Cell(object):
  101.     def __init__(self, char):
  102.         self.char = char
  103.         self.tag = 0
  104.         self.index = 0
  105.         self.neighbors = None
  106.  
  107.  
  108. class Grid(object):
  109.  
  110.     def __init__(self, cells):
  111.         self.height, self.width = len(cells), len(cells[0])
  112.         self.cells = cells
  113.  
  114.     def __contains__(self, pos):
  115.         y, x = pos
  116.         return 0 <= y < self.height and 0 <= x < self.width
  117.  
  118.     def __getitem__(self, pos):
  119.         y, x = pos
  120.         return self.cells[y][x]
  121.  
  122.     def neighbors(self, y, x):
  123.         for dy, dx in ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1),
  124.                        (1, 0), (1, 1)):
  125.             if (y + dy, x + dx) in self:
  126.                 yield y + dy, x + dx
  127.  
  128.  
  129. def parse_grid(grid_str, width, height):
  130.  
  131.     # Split the grid string into lines.
  132.     lines = [line.rstrip() for line in grid_str.splitlines()[1:]]
  133.  
  134.     # Pad the top and bottom.
  135.     top = (height - len(lines)) // 2
  136.     bottom = (height - len(lines) + 1) // 2
  137.     lines = ([''] * top + lines + [''] * bottom)[:height]
  138.  
  139.     # Pad the left and right sides.
  140.     max_len = max(len(line) for line in lines)
  141.     left = (width - max_len) // 2
  142.     lines = [' ' * left + line.ljust(width - left)[:width - left]
  143.              for line in lines]
  144.  
  145.     # Create the grid.
  146.     cells = [[Cell(char) for char in line] for line in lines]
  147.     return Grid(cells)
  148.  
  149.  
  150. class Engine(object):
  151.  
  152.     def __init__(self, grid):
  153.         self.grid = grid
  154.         self.y = 1
  155.         self.x = 1
  156.         self.goal = (10,20) #Target
  157.         self.limit = LIMIT
  158.         self.tag = 1
  159.         self.nodes = {}
  160.         self.path = []
  161.         self.dirty = True
  162.         self.debug = DEBUG
  163.  
  164.    
  165.  
  166.     def update_path(self):
  167.         if not self.dirty:
  168.             return
  169.         self.dirty = False
  170.         self.tag += 1
  171.         def neighbors(pos):
  172.             cell = self.grid[pos]
  173.             if cell.neighbors is None:
  174.                 y, x = pos
  175.                 cell.neighbors = []
  176.                 for neighbor_y, neighbor_x in self.grid.neighbors(y, x):
  177.                     if self.grid[neighbor_y, neighbor_x].char != '#':
  178.                         cell.neighbors.append((neighbor_y, neighbor_x))
  179.             return cell.neighbors
  180.         def goal(pos):
  181.             return pos == self.goal
  182.         def cost(from_pos, to_pos):
  183.             from_y, from_x = from_pos
  184.             to_y, to_x = to_pos
  185.             return 14 if to_y - from_y and to_x - from_x else 10
  186.         def estimate(pos):
  187.             y, x = pos
  188.             goal_y, goal_x = self.goal
  189.             dy, dx = abs(goal_y - y), abs(goal_x - x)
  190.             return min(dy, dx) * 14 + abs(dy - dx) * 10
  191.         def debug(nodes):
  192.             self.nodes = nodes
  193.         self.path = astar((self.y, self.x), neighbors, goal, 0, cost,
  194.                           estimate, self.limit)
  195.  
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.  
  203.  
  204. grid = parse_grid(DUNGEON, WIDTH, HEIGHT)
  205. engine = Engine(grid)
  206. engine.update_path()
  207. print(engine.path)
  208.  
  209.  
  210.  
  211. from http.server import BaseHTTPRequestHandler, HTTPServer
  212.  
  213. class StoreHandler(BaseHTTPRequestHandler):
  214.  
  215.     def do_GET(self):
  216.         print(self.path)
  217.         aud = self.path
  218.         print("Path : ", self.path)
  219.  
  220.         result = re.search(r'\/[0-9][0-9][0-9]', aud)
  221.         if result.group(0) != None:
  222.             print('ok')
  223.             result = re.search(r'[0-9][0-9][0-9]', aud)
  224.             aud = int(result.group(0))
  225.             if aud == 100:
  226.                 x=10
  227.                 y=20
  228.             elif aud == 101:
  229.                 x=3
  230.                 y=20
  231.            
  232.             engine.goal = (x,y)
  233.             engine.dirty = True
  234.             print(engine.goal)
  235.             engine.update_path()
  236.             print(engine.path)
  237.            
  238.             command = ""
  239.  
  240.             for i in range(1,len(engine.path)-1):
  241.                 if engine.path[i-1][0] > engine.path[i][0]:
  242.                     command += "T"
  243.                 elif engine.path[i-1][0] < engine.path[i][0]:
  244.                     command += "D"
  245.  
  246.                 if engine.path[i-1][1] < engine.path[i][1]:
  247.                     command += "R"
  248.                 elif engine.path[i-1][1] > engine.path[i][1]:
  249.                     command += "L"
  250.             print(command)
  251.             ser.write(command.encode('ascii'))
  252.  
  253.     def do_POST(self):
  254.             self.send_response(200)
  255.  
  256.  
  257. server = HTTPServer(('', 8080), StoreHandler)
  258. server.serve_forever()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement