NaroxEG

Algorithms Simulation

Nov 2nd, 2026
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.30 KB | None | 0 0
  1. import pygame
  2. import math
  3. import time
  4. from queue import PriorityQueue
  5.  
  6. # Settings
  7. WIDTH = 700
  8. ROWS, COLS = 14, 14
  9. CELL = WIDTH // COLS
  10. HEIGHT = ROWS * CELL
  11.  
  12. STEP_DELAY = 400
  13. PATH_DELAY = 180
  14.  
  15. # Colors
  16. WHITE = (245, 245, 245)
  17. BLACK = (40, 40, 40)
  18. GREY = (210, 210, 210)
  19. ORANGE = (255, 140, 0)
  20. TURQUOISE = (0, 206, 209)
  21. RED = (250, 128, 114)
  22. GREEN = (152, 251, 152)
  23. PURPLE = (138, 43, 226)
  24. YELLOW = (255, 215, 0)
  25. BLUE = (30, 100, 220)
  26. GOLD = (255, 235, 100)
  27.  
  28. pygame.init()
  29. WIN = pygame.display.set_mode((WIDTH, HEIGHT))
  30. pygame.display.set_caption("1: Hill Climbing | 2: Beam Search | 3: JPS | R: Reset")
  31.  
  32.  
  33. # Spot class
  34. class Spot:
  35.     def __init__(self, r, c):
  36.         self.r = r
  37.         self.c = c
  38.         self.color = WHITE
  39.  
  40.     def is_barrier(self):
  41.         return self.color == BLACK
  42.  
  43.     def draw(self):
  44.         pygame.draw.rect(WIN, self.color,
  45.                          (self.c * CELL, self.r * CELL, CELL, CELL))
  46.  
  47.     def neighbors(self, grid):
  48.         directions = [
  49.             (-1, 0), (1, 0), (0, -1), (0, 1),
  50.             (-1, -1), (-1, 1), (1, -1), (1, 1)
  51.         ]
  52.  
  53.         result = []
  54.  
  55.         for dr, dc in directions:
  56.             r, c = self.r + dr, self.c + dc
  57.  
  58.             if 0 <= r < ROWS and 0 <= c < COLS:
  59.                 if grid[r][c].is_barrier():
  60.                     continue
  61.  
  62.                 if dr and dc:
  63.                     if (grid[self.r + dr][self.c].is_barrier()
  64.                             and grid[self.r][self.c + dc].is_barrier()):
  65.                         continue
  66.  
  67.                 result.append(grid[r][c])
  68.  
  69.         return result
  70.  
  71.  
  72. # Basic functions
  73. def h(a, b):
  74.     return math.hypot(a.r - b.r, a.c - b.c)
  75.  
  76.  
  77. def is_free(grid, r, c):
  78.     return 0 <= r < ROWS and 0 <= c < COLS and not grid[r][c].is_barrier()
  79.  
  80.  
  81. def is_blocked(grid, r, c):
  82.     return 0 <= r < ROWS and 0 <= c < COLS and grid[r][c].is_barrier()
  83.  
  84.  
  85. # Drawing functions
  86. def draw_arrow(p1, p2, color, width=3):
  87.     x1, y1 = p1.c * CELL + CELL // 2, p1.r * CELL + CELL // 2
  88.     x2, y2 = p2.c * CELL + CELL // 2, p2.r * CELL + CELL // 2
  89.  
  90.     angle = math.atan2(y2 - y1, x2 - x1)
  91.  
  92.     ex = x2 - math.cos(angle) * 8
  93.     ey = y2 - math.sin(angle) * 8
  94.  
  95.     pygame.draw.line(WIN, color, (x1, y1), (ex, ey), width)
  96.  
  97.     size = 11
  98.     left = (ex - size * math.cos(angle - math.pi / 6),
  99.             ey - size * math.sin(angle - math.pi / 6))
  100.     right = (ex - size * math.cos(angle + math.pi / 6),
  101.              ey - size * math.sin(angle + math.pi / 6))
  102.  
  103.     pygame.draw.polygon(WIN, color, [(ex, ey), left, right])
  104.  
  105.  
  106. def draw(grid, arrows=None, path_arrows=None):
  107.     WIN.fill(WHITE)
  108.  
  109.     for row in grid:
  110.         for spot in row:
  111.             spot.draw()
  112.  
  113.     for r in range(ROWS):
  114.         pygame.draw.line(WIN, GREY, (0, r * CELL), (WIDTH, r * CELL))
  115.  
  116.     for c in range(COLS):
  117.         pygame.draw.line(WIN, GREY, (c * CELL, 0), (c * CELL, HEIGHT))
  118.  
  119.     if arrows:
  120.         for a, b in arrows:
  121.             draw_arrow(a, b, BLUE)
  122.  
  123.     if path_arrows:
  124.         for a, b in path_arrows:
  125.             draw_arrow(a, b, GOLD, 4)
  126.  
  127.     pygame.display.update()
  128.  
  129.  
  130. def clear_paths(grid, start, end):
  131.     for row in grid:
  132.         for spot in row:
  133.             if spot != start and spot != end and not spot.is_barrier():
  134.                 spot.color = WHITE
  135.  
  136.  
  137. def show_path(came_from, end, grid, start, arrows, path_arrows):
  138.     path = []
  139.     current = end
  140.  
  141.     while current in came_from and came_from[current]:
  142.         previous = came_from[current]
  143.         path.append((previous, current))
  144.         current = previous
  145.  
  146.     path.reverse()
  147.     cost = 0
  148.  
  149.     for a, b in path:
  150.         cost += h(a, b)
  151.  
  152.         dr = 0 if a.r == b.r else (1 if b.r > a.r else -1)
  153.         dc = 0 if a.c == b.c else (1 if b.c > a.c else -1)
  154.  
  155.         r, c = a.r, a.c
  156.         previous = a
  157.  
  158.         while (r, c) != (b.r, b.c):
  159.             r += dr
  160.             c += dc
  161.             spot = grid[r][c]
  162.  
  163.             if spot != start and spot != end:
  164.                 spot.color = PURPLE
  165.  
  166.             path_arrows.append((previous, spot))
  167.             previous = spot
  168.  
  169.             draw(grid, arrows, path_arrows)
  170.             pygame.time.delay(PATH_DELAY)
  171.  
  172.     return cost
  173.  
  174.  
  175. # 1. Hill Climbing
  176. def hill_climbing(grid, start, end):
  177.     current = start
  178.     came_from = {start: None}
  179.     arrows = []
  180.     path_arrows = []
  181.     visited = 0
  182.     total_time = 0
  183.  
  184.     while current != end:
  185.         t0 = time.perf_counter()
  186.  
  187.         neighbors = [n for n in current.neighbors(grid) if n not in came_from]
  188.  
  189.         if not neighbors:
  190.             break
  191.  
  192.         best = min(neighbors, key=lambda n: h(n, end))
  193.  
  194.         if h(best, end) >= h(current, end):
  195.             break
  196.  
  197.         came_from[best] = current
  198.         arrows.append((current, best))
  199.         current = best
  200.         visited += 1
  201.  
  202.         total_time += (time.perf_counter() - t0) * 1000
  203.  
  204.         if current != end:
  205.             current.color = RED
  206.  
  207.         draw(grid, arrows, path_arrows)
  208.         pygame.time.delay(STEP_DELAY)
  209.  
  210.     cost = show_path(came_from, end, grid, start, arrows, path_arrows)
  211.  
  212.     return current == end, visited, cost, total_time
  213.  
  214.  
  215. # 2. Beam Search
  216. def beam_search(grid, start, end, beta=2):
  217.     beam = [start]
  218.     came_from = {start: None}
  219.     arrows = []
  220.     path_arrows = []
  221.     visited = 0
  222.     found = False
  223.     total_time = 0
  224.  
  225.     while beam and not found:
  226.         t0 = time.perf_counter()
  227.         candidates = []
  228.  
  229.         for current in beam:
  230.             if current == end:
  231.                 found = True
  232.                 break
  233.  
  234.             for n in current.neighbors(grid):
  235.                 if n not in came_from:
  236.                     came_from[n] = current
  237.                     candidates.append(n)
  238.  
  239.                     if n != end:
  240.                         n.color = GREEN
  241.  
  242.         if found or not candidates:
  243.             total_time += (time.perf_counter() - t0) * 1000
  244.             break
  245.  
  246.         candidates.sort(key=lambda n: h(n, end))
  247.  
  248.         for n in candidates[beta:]:
  249.             if n != end:
  250.                 n.color = WHITE
  251.  
  252.         beam = candidates[:beta]
  253.  
  254.         for n in beam:
  255.             if n != end:
  256.                 n.color = RED
  257.  
  258.             arrows.append((came_from[n], n))
  259.             visited += 1
  260.  
  261.         total_time += (time.perf_counter() - t0) * 1000
  262.  
  263.         draw(grid, arrows, path_arrows)
  264.         pygame.time.delay(STEP_DELAY)
  265.  
  266.     cost = show_path(came_from, end, grid, start, arrows, path_arrows)
  267.  
  268.     return found, visited, cost, total_time
  269.  
  270.  
  271. # 3. Jump Point Search
  272. def get_jps_dirs(grid, current, parent):
  273.     if parent is None:
  274.         return [
  275.             (-1, 0), (1, 0), (0, -1), (0, 1),
  276.             (-1, -1), (-1, 1), (1, -1), (1, 1)
  277.         ]
  278.  
  279.     r, c = current.r, current.c
  280.     dr = 0 if r == parent.r else (1 if r > parent.r else -1)
  281.     dc = 0 if c == parent.c else (1 if c > parent.c else -1)
  282.  
  283.     dirs = []
  284.  
  285.     if dr and dc:
  286.         dirs.extend([(dr, 0), (0, dc), (dr, dc)])
  287.  
  288.         if is_blocked(grid, r - dr, c) and is_free(grid, r - dr, c + dc):
  289.             dirs.append((-dr, dc))
  290.  
  291.         if is_blocked(grid, r, c - dc) and is_free(grid, r + dr, c - dc):
  292.             dirs.append((dr, -dc))
  293.  
  294.     elif dr:
  295.         dirs.append((dr, 0))
  296.  
  297.         if is_blocked(grid, r, c - 1) and is_free(grid, r + dr, c - 1):
  298.             dirs.append((dr, -1))
  299.  
  300.         if is_blocked(grid, r, c + 1) and is_free(grid, r + dr, c + 1):
  301.             dirs.append((dr, 1))
  302.  
  303.     else:
  304.         dirs.append((0, dc))
  305.  
  306.         if is_blocked(grid, r - 1, c) and is_free(grid, r - 1, c + dc):
  307.             dirs.append((-1, dc))
  308.  
  309.         if is_blocked(grid, r + 1, c) and is_free(grid, r + 1, c + dc):
  310.             dirs.append((1, dc))
  311.  
  312.     return dirs
  313.  
  314.  
  315. def jump(grid, r, c, dr, dc, end):
  316.     nr, nc = r + dr, c + dc
  317.  
  318.     if not is_free(grid, nr, nc):
  319.         return None
  320.  
  321.     if dr and dc:
  322.         if is_blocked(grid, r + dr, c) and is_blocked(grid, r, c + dc):
  323.             return None
  324.  
  325.     if (nr, nc) == (end.r, end.c):
  326.         return grid[nr][nc]
  327.  
  328.     if dr and dc:
  329.         if ((is_blocked(grid, nr - dr, nc) and is_free(grid, nr - dr, nc + dc))
  330.                 or (is_blocked(grid, nr, nc - dc) and is_free(grid, nr + dr, nc - dc))):
  331.             return grid[nr][nc]
  332.  
  333.         if (jump(grid, nr, nc, dr, 0, end)
  334.                 or jump(grid, nr, nc, 0, dc, end)):
  335.             return grid[nr][nc]
  336.  
  337.     elif dr:
  338.         if ((is_blocked(grid, nr, nc - 1) and is_free(grid, nr + dr, nc - 1))
  339.                 or (is_blocked(grid, nr, nc + 1) and is_free(grid, nr + dr, nc + 1))):
  340.             return grid[nr][nc]
  341.  
  342.     else:
  343.         if ((is_blocked(grid, nr - 1, nc) and is_free(grid, nr - 1, nc + dc))
  344.                 or (is_blocked(grid, nr + 1, nc) and is_free(grid, nr + 1, nc + dc))):
  345.             return grid[nr][nc]
  346.  
  347.     return jump(grid, nr, nc, dr, dc, end)
  348.  
  349.  
  350. def jps(grid, start, end):
  351.     pq = PriorityQueue()
  352.     pq.put((0, 0, start))
  353.  
  354.     came_from = {start: None}
  355.     g_score = {start: 0}
  356.     closed = set()
  357.  
  358.     arrows = []
  359.     path_arrows = []
  360.     visited = 0
  361.     count = 0
  362.     total_time = 0
  363.  
  364.     while not pq.empty():
  365.         t0 = time.perf_counter()
  366.         current = pq.get()[2]
  367.  
  368.         if current in closed:
  369.             total_time += (time.perf_counter() - t0) * 1000
  370.             continue
  371.  
  372.         if current == end:
  373.             total_time += (time.perf_counter() - t0) * 1000
  374.             break
  375.  
  376.         closed.add(current)
  377.         visited += 1
  378.  
  379.         if current != start:
  380.             current.color = RED
  381.  
  382.         for dr, dc in get_jps_dirs(grid, current, came_from[current]):
  383.             point = jump(grid, current.r, current.c, dr, dc, end)
  384.  
  385.             if point is None or point in closed:
  386.                 continue
  387.  
  388.             new_cost = g_score[current] + h(current, point)
  389.  
  390.             if point not in g_score or new_cost < g_score[point]:
  391.                 g_score[point] = new_cost
  392.                 came_from[point] = current
  393.  
  394.                 count += 1
  395.                 priority = new_cost + h(point, end)
  396.                 pq.put((priority, count, point))
  397.  
  398.                 arrows.append((current, point))
  399.  
  400.                 if point != end:
  401.                     point.color = YELLOW
  402.  
  403.         total_time += (time.perf_counter() - t0) * 1000
  404.  
  405.         draw(grid, arrows, path_arrows)
  406.         pygame.time.delay(STEP_DELAY)
  407.  
  408.     cost = show_path(came_from, end, grid, start, arrows, path_arrows)
  409.  
  410.     return end in came_from, visited, cost, total_time
  411.  
  412.  
  413. # Create the map
  414. def create_grid():
  415.     grid = [[Spot(r, c) for c in range(COLS)] for r in range(ROWS)]
  416.  
  417.     for c in range(2, 6):
  418.         grid[8][c].color = BLACK
  419.  
  420.     for r in range(3, 8):
  421.         grid[r][9].color = BLACK
  422.  
  423.     start = grid[11][2]
  424.     end = grid[2][12]
  425.  
  426.     start.color = ORANGE
  427.     end.color = TURQUOISE
  428.  
  429.     return grid, start, end
  430.  
  431.  
  432. # Main program
  433. def main():
  434.     grid, start, end = create_grid()
  435.     draw(grid)
  436.  
  437.     running = True
  438.  
  439.     while running:
  440.         for event in pygame.event.get():
  441.  
  442.             if event.type == pygame.QUIT:
  443.                 running = False
  444.  
  445.             if event.type == pygame.KEYDOWN:
  446.  
  447.                 if event.key == pygame.K_1:
  448.                     clear_paths(grid, start, end)
  449.                     found, visited, cost, ms = hill_climbing(grid, start, end)
  450.                     name = "Hill Climbing"
  451.  
  452.                 elif event.key == pygame.K_2:
  453.                     clear_paths(grid, start, end)
  454.                     found, visited, cost, ms = beam_search(grid, start, end)
  455.                     name = "Beam Search"
  456.  
  457.                 elif event.key == pygame.K_3:
  458.                     clear_paths(grid, start, end)
  459.                     found, visited, cost, ms = jps(grid, start, end)
  460.                     name = "JPS"
  461.  
  462.                 elif event.key == pygame.K_r:
  463.                     clear_paths(grid, start, end)
  464.                     draw(grid)
  465.                     pygame.display.set_caption(
  466.                         "1: Hill Climbing | 2: Beam Search | 3: JPS | R: Reset"
  467.                     )
  468.                     continue
  469.  
  470.                 else:
  471.                     continue
  472.  
  473.                 pygame.display.set_caption(
  474.                     f"{name} | Visited: {visited} | Cost: {cost:.1f} | Time: {ms:.2f}ms"
  475.                 )
  476.  
  477.     pygame.quit()
  478.  
  479.  
  480. if __name__ == "__main__":
  481.     main()
Advertisement
Add Comment
Please, Sign In to add comment