Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pygame
- import math
- import time
- from queue import PriorityQueue
- # Settings
- WIDTH = 700
- ROWS, COLS = 14, 14
- CELL = WIDTH // COLS
- HEIGHT = ROWS * CELL
- STEP_DELAY = 400
- PATH_DELAY = 180
- # Colors
- WHITE = (245, 245, 245)
- BLACK = (40, 40, 40)
- GREY = (210, 210, 210)
- ORANGE = (255, 140, 0)
- TURQUOISE = (0, 206, 209)
- RED = (250, 128, 114)
- GREEN = (152, 251, 152)
- PURPLE = (138, 43, 226)
- YELLOW = (255, 215, 0)
- BLUE = (30, 100, 220)
- GOLD = (255, 235, 100)
- pygame.init()
- WIN = pygame.display.set_mode((WIDTH, HEIGHT))
- pygame.display.set_caption("1: Hill Climbing | 2: Beam Search | 3: JPS | R: Reset")
- # Spot class
- class Spot:
- def __init__(self, r, c):
- self.r = r
- self.c = c
- self.color = WHITE
- def is_barrier(self):
- return self.color == BLACK
- def draw(self):
- pygame.draw.rect(WIN, self.color,
- (self.c * CELL, self.r * CELL, CELL, CELL))
- def neighbors(self, grid):
- directions = [
- (-1, 0), (1, 0), (0, -1), (0, 1),
- (-1, -1), (-1, 1), (1, -1), (1, 1)
- ]
- result = []
- for dr, dc in directions:
- r, c = self.r + dr, self.c + dc
- if 0 <= r < ROWS and 0 <= c < COLS:
- if grid[r][c].is_barrier():
- continue
- if dr and dc:
- if (grid[self.r + dr][self.c].is_barrier()
- and grid[self.r][self.c + dc].is_barrier()):
- continue
- result.append(grid[r][c])
- return result
- # Basic functions
- def h(a, b):
- return math.hypot(a.r - b.r, a.c - b.c)
- def is_free(grid, r, c):
- return 0 <= r < ROWS and 0 <= c < COLS and not grid[r][c].is_barrier()
- def is_blocked(grid, r, c):
- return 0 <= r < ROWS and 0 <= c < COLS and grid[r][c].is_barrier()
- # Drawing functions
- def draw_arrow(p1, p2, color, width=3):
- x1, y1 = p1.c * CELL + CELL // 2, p1.r * CELL + CELL // 2
- x2, y2 = p2.c * CELL + CELL // 2, p2.r * CELL + CELL // 2
- angle = math.atan2(y2 - y1, x2 - x1)
- ex = x2 - math.cos(angle) * 8
- ey = y2 - math.sin(angle) * 8
- pygame.draw.line(WIN, color, (x1, y1), (ex, ey), width)
- size = 11
- left = (ex - size * math.cos(angle - math.pi / 6),
- ey - size * math.sin(angle - math.pi / 6))
- right = (ex - size * math.cos(angle + math.pi / 6),
- ey - size * math.sin(angle + math.pi / 6))
- pygame.draw.polygon(WIN, color, [(ex, ey), left, right])
- def draw(grid, arrows=None, path_arrows=None):
- WIN.fill(WHITE)
- for row in grid:
- for spot in row:
- spot.draw()
- for r in range(ROWS):
- pygame.draw.line(WIN, GREY, (0, r * CELL), (WIDTH, r * CELL))
- for c in range(COLS):
- pygame.draw.line(WIN, GREY, (c * CELL, 0), (c * CELL, HEIGHT))
- if arrows:
- for a, b in arrows:
- draw_arrow(a, b, BLUE)
- if path_arrows:
- for a, b in path_arrows:
- draw_arrow(a, b, GOLD, 4)
- pygame.display.update()
- def clear_paths(grid, start, end):
- for row in grid:
- for spot in row:
- if spot != start and spot != end and not spot.is_barrier():
- spot.color = WHITE
- def show_path(came_from, end, grid, start, arrows, path_arrows):
- path = []
- current = end
- while current in came_from and came_from[current]:
- previous = came_from[current]
- path.append((previous, current))
- current = previous
- path.reverse()
- cost = 0
- for a, b in path:
- cost += h(a, b)
- dr = 0 if a.r == b.r else (1 if b.r > a.r else -1)
- dc = 0 if a.c == b.c else (1 if b.c > a.c else -1)
- r, c = a.r, a.c
- previous = a
- while (r, c) != (b.r, b.c):
- r += dr
- c += dc
- spot = grid[r][c]
- if spot != start and spot != end:
- spot.color = PURPLE
- path_arrows.append((previous, spot))
- previous = spot
- draw(grid, arrows, path_arrows)
- pygame.time.delay(PATH_DELAY)
- return cost
- # 1. Hill Climbing
- def hill_climbing(grid, start, end):
- current = start
- came_from = {start: None}
- arrows = []
- path_arrows = []
- visited = 0
- total_time = 0
- while current != end:
- t0 = time.perf_counter()
- neighbors = [n for n in current.neighbors(grid) if n not in came_from]
- if not neighbors:
- break
- best = min(neighbors, key=lambda n: h(n, end))
- if h(best, end) >= h(current, end):
- break
- came_from[best] = current
- arrows.append((current, best))
- current = best
- visited += 1
- total_time += (time.perf_counter() - t0) * 1000
- if current != end:
- current.color = RED
- draw(grid, arrows, path_arrows)
- pygame.time.delay(STEP_DELAY)
- cost = show_path(came_from, end, grid, start, arrows, path_arrows)
- return current == end, visited, cost, total_time
- # 2. Beam Search
- def beam_search(grid, start, end, beta=2):
- beam = [start]
- came_from = {start: None}
- arrows = []
- path_arrows = []
- visited = 0
- found = False
- total_time = 0
- while beam and not found:
- t0 = time.perf_counter()
- candidates = []
- for current in beam:
- if current == end:
- found = True
- break
- for n in current.neighbors(grid):
- if n not in came_from:
- came_from[n] = current
- candidates.append(n)
- if n != end:
- n.color = GREEN
- if found or not candidates:
- total_time += (time.perf_counter() - t0) * 1000
- break
- candidates.sort(key=lambda n: h(n, end))
- for n in candidates[beta:]:
- if n != end:
- n.color = WHITE
- beam = candidates[:beta]
- for n in beam:
- if n != end:
- n.color = RED
- arrows.append((came_from[n], n))
- visited += 1
- total_time += (time.perf_counter() - t0) * 1000
- draw(grid, arrows, path_arrows)
- pygame.time.delay(STEP_DELAY)
- cost = show_path(came_from, end, grid, start, arrows, path_arrows)
- return found, visited, cost, total_time
- # 3. Jump Point Search
- def get_jps_dirs(grid, current, parent):
- if parent is None:
- return [
- (-1, 0), (1, 0), (0, -1), (0, 1),
- (-1, -1), (-1, 1), (1, -1), (1, 1)
- ]
- r, c = current.r, current.c
- dr = 0 if r == parent.r else (1 if r > parent.r else -1)
- dc = 0 if c == parent.c else (1 if c > parent.c else -1)
- dirs = []
- if dr and dc:
- dirs.extend([(dr, 0), (0, dc), (dr, dc)])
- if is_blocked(grid, r - dr, c) and is_free(grid, r - dr, c + dc):
- dirs.append((-dr, dc))
- if is_blocked(grid, r, c - dc) and is_free(grid, r + dr, c - dc):
- dirs.append((dr, -dc))
- elif dr:
- dirs.append((dr, 0))
- if is_blocked(grid, r, c - 1) and is_free(grid, r + dr, c - 1):
- dirs.append((dr, -1))
- if is_blocked(grid, r, c + 1) and is_free(grid, r + dr, c + 1):
- dirs.append((dr, 1))
- else:
- dirs.append((0, dc))
- if is_blocked(grid, r - 1, c) and is_free(grid, r - 1, c + dc):
- dirs.append((-1, dc))
- if is_blocked(grid, r + 1, c) and is_free(grid, r + 1, c + dc):
- dirs.append((1, dc))
- return dirs
- def jump(grid, r, c, dr, dc, end):
- nr, nc = r + dr, c + dc
- if not is_free(grid, nr, nc):
- return None
- if dr and dc:
- if is_blocked(grid, r + dr, c) and is_blocked(grid, r, c + dc):
- return None
- if (nr, nc) == (end.r, end.c):
- return grid[nr][nc]
- if dr and dc:
- if ((is_blocked(grid, nr - dr, nc) and is_free(grid, nr - dr, nc + dc))
- or (is_blocked(grid, nr, nc - dc) and is_free(grid, nr + dr, nc - dc))):
- return grid[nr][nc]
- if (jump(grid, nr, nc, dr, 0, end)
- or jump(grid, nr, nc, 0, dc, end)):
- return grid[nr][nc]
- elif dr:
- if ((is_blocked(grid, nr, nc - 1) and is_free(grid, nr + dr, nc - 1))
- or (is_blocked(grid, nr, nc + 1) and is_free(grid, nr + dr, nc + 1))):
- return grid[nr][nc]
- else:
- if ((is_blocked(grid, nr - 1, nc) and is_free(grid, nr - 1, nc + dc))
- or (is_blocked(grid, nr + 1, nc) and is_free(grid, nr + 1, nc + dc))):
- return grid[nr][nc]
- return jump(grid, nr, nc, dr, dc, end)
- def jps(grid, start, end):
- pq = PriorityQueue()
- pq.put((0, 0, start))
- came_from = {start: None}
- g_score = {start: 0}
- closed = set()
- arrows = []
- path_arrows = []
- visited = 0
- count = 0
- total_time = 0
- while not pq.empty():
- t0 = time.perf_counter()
- current = pq.get()[2]
- if current in closed:
- total_time += (time.perf_counter() - t0) * 1000
- continue
- if current == end:
- total_time += (time.perf_counter() - t0) * 1000
- break
- closed.add(current)
- visited += 1
- if current != start:
- current.color = RED
- for dr, dc in get_jps_dirs(grid, current, came_from[current]):
- point = jump(grid, current.r, current.c, dr, dc, end)
- if point is None or point in closed:
- continue
- new_cost = g_score[current] + h(current, point)
- if point not in g_score or new_cost < g_score[point]:
- g_score[point] = new_cost
- came_from[point] = current
- count += 1
- priority = new_cost + h(point, end)
- pq.put((priority, count, point))
- arrows.append((current, point))
- if point != end:
- point.color = YELLOW
- total_time += (time.perf_counter() - t0) * 1000
- draw(grid, arrows, path_arrows)
- pygame.time.delay(STEP_DELAY)
- cost = show_path(came_from, end, grid, start, arrows, path_arrows)
- return end in came_from, visited, cost, total_time
- # Create the map
- def create_grid():
- grid = [[Spot(r, c) for c in range(COLS)] for r in range(ROWS)]
- for c in range(2, 6):
- grid[8][c].color = BLACK
- for r in range(3, 8):
- grid[r][9].color = BLACK
- start = grid[11][2]
- end = grid[2][12]
- start.color = ORANGE
- end.color = TURQUOISE
- return grid, start, end
- # Main program
- def main():
- grid, start, end = create_grid()
- draw(grid)
- running = True
- while running:
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- running = False
- if event.type == pygame.KEYDOWN:
- if event.key == pygame.K_1:
- clear_paths(grid, start, end)
- found, visited, cost, ms = hill_climbing(grid, start, end)
- name = "Hill Climbing"
- elif event.key == pygame.K_2:
- clear_paths(grid, start, end)
- found, visited, cost, ms = beam_search(grid, start, end)
- name = "Beam Search"
- elif event.key == pygame.K_3:
- clear_paths(grid, start, end)
- found, visited, cost, ms = jps(grid, start, end)
- name = "JPS"
- elif event.key == pygame.K_r:
- clear_paths(grid, start, end)
- draw(grid)
- pygame.display.set_caption(
- "1: Hill Climbing | 2: Beam Search | 3: JPS | R: Reset"
- )
- continue
- else:
- continue
- pygame.display.set_caption(
- f"{name} | Visited: {visited} | Cost: {cost:.1f} | Time: {ms:.2f}ms"
- )
- pygame.quit()
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment