Skip to content

Commit 13c5161

Browse files
Update Algorithm Sketch(script)
1 parent 166267f commit 13c5161

File tree

1 file changed

+49
-105
lines changed

1 file changed

+49
-105
lines changed

Algorithm Sketch(script)

Lines changed: 49 additions & 105 deletions
Original file line numberDiff line numberDiff line change
@@ -3,112 +3,56 @@ turning the algorithms to classes may help me reduce loops (make it efficient).
33

44
This Python script uses the Pygame library to visualize and compare Dijkstra's algorithm and A* algorithm for pathfinding in a grid-based environment. Here's a breakdown of the code:
55
(Additions- BFS ,DFS)
6-
1. Import Statements
7-
8-
import random
9-
import pygame
10-
import heapq
11-
from collections import deque
12-
random: Module for generating pseudo-random numbers.
13-
pygame: Library for creating games and multimedia applications.
14-
heapq: Module for heap queue algorithm.
15-
deque: Double-ended queue implementation for efficiently adding and removing elements.
16-
2. Constants
17-
18-
# Color Constants
19-
WHITE = (255, 255, 255)
20-
BLACK = (0, 0, 0)
21-
RED = (255, 0, 0)
22-
GREEN = (0, 255, 0)
23-
BLUE = (0, 0, 255)
24-
YELLOW = (255, 255, 0)
25-
GRAY = (128, 128, 128)
26-
27-
# Grid Constants
28-
GRID_SIZE = 20
29-
CELL_SIZE = 30
30-
SCREEN_SIZE = (GRID_SIZE * CELL_SIZE, GRID_SIZE * CELL_SIZE)
31-
32-
# Start and End Points
33-
START = (0, 0)
34-
END = (GRID_SIZE - 1, GRID_SIZE - 1)
35-
Constants for colors and grid-related parameters.
36-
3. Pygame Initialization
37-
38-
pygame.init()
39-
screen = pygame.display.set_mode(SCREEN_SIZE)
40-
pygame.display.set_caption("Pathfinding Visualization")
41-
Initializes the Pygame library, creates a window with the specified size, and sets the window caption.
42-
4. Drawing Functions
43-
python
44-
45-
# Function to draw the grid
46-
def draw_grid():
47-
# ...
48-
49-
# Function to draw a colored cell at a specific position
50-
def draw_cell(color, position):
51-
# ...
52-
53-
# Function to visualize the path with a delay
54-
def visualize_path(path, color):
55-
# ...
56-
57-
# Reset the screen, draw the grid, and update the display
58-
def reset():
59-
# ...
60-
5. Pathfinding Algorithms
61-
62-
63-
# Dijkstra's algorithm
64-
def dijkstra(start, end, obstacles):
65-
# ...
66-
67-
# A* algorithm
68-
def astar(start, end, obstacles):
69-
# ...
70-
71-
# DFS algorithm
72-
def dfs(start, end, obstacles):
73-
# ...
74-
75-
# BFS algorithm
76-
def bfs(start, end, obstacles):
77-
# ...
78-
79-
# Heuristic function for A*
80-
def heuristic(point, goal):
81-
# ...
82-
83-
# Function to get valid neighbors for a cell
84-
def neighbors(cell):
85-
# ...
86-
6. Main Function
87-
python
88-
89-
def main():
90-
# ...
91-
92-
if __name__ == "__main__":
93-
main()
94-
The main function initializes the screen, handles user input, and runs various pathfinding algorithms based on the user's actions.
95-
7. User Interface and Input Handling
96-
The code responds to user input events (e.g., mouse clicks, key presses) to set start and end points, draw obstacles, and initiate pathfinding algorithms.
97-
8. Running Pathfinding Algorithms
98-
When the user presses the spacebar (pygame.K_SPACE), Dijkstra's, A*, DFS, and BFS algorithms are run simultaneously, and the time taken by each algorithm is printed.
99-
9. Pygame Event Loop
100-
The program enters a Pygame event loop (pygame.event.get()) to handle user input, update the display, and keep the application running until the user closes the window (pygame.QUIT event).
101-
10. Obstacle Drawing
102-
The code allows users to draw obstacles on the grid by clicking and dragging the mouse.
103-
11. Cleanup
104-
105-
106-
pygame.quit()
107-
Properly shuts down the Pygame library when the program exits.
108-
109-
The main function is called if the script is executed directly.
110-
The script allows the user to set start and end points, mark cells as obstacles, and compare Dijkstra's and A* algorithms in finding the shortest path.
6+
draw_grid(): This function is responsible for drawing the grid lines on the Pygame window. It iterates over the screen size and draws horizontal and vertical lines to create a grid.
1117

8+
Let's dive deeper into the functionality of each function:
9+
10+
1. `draw_grid()`: This foundational function sets up the visual representation of the grid system within the Pygame window.
11+
It meticulously iterates through the dimensions of the screen, meticulously crafting the grid pattern by drawing horizontal and vertical lines, ensuring a clear and structured layout.
12+
13+
2. `draw_cell(color, position)`: A critical function in the visualization process, `draw_cell()` brings individual cells to life within the grid.
14+
Given parameters for color and position, it utilizes Pygame's drawing capabilities to create a rectangular representation of the cell, ensuring each cell is distinctly identifiable with its specified color at the designated position.
15+
16+
3. `visualize_path(path, color)`: This function adds an extra layer of insight into the algorithm's decision-making process by visually representing the path taken.
17+
It meticulously traverses through each cell in the provided path, dynamically highlighting them with the specified color, offering users a real-time glimpse into the algorithm's progression.
18+
19+
4. `reset()`: Serving as the reset mechanism, `reset()` ensures a clean slate for each algorithm execution. By filling the Pygame window with a black color and redrawing the grid,
20+
it wipes away any remnants of previous visualizations, priming the environment for a fresh algorithm run or visualization.
21+
22+
5. `dijkstra(start, end, obstacles)`: At the heart of this function lies the implementation of Dijkstra's algorithm,
23+
meticulously navigating the grid to uncover the shortest path from the start to the end node. Leveraging a priority queue, it meticulously selects the next node to explore, ensuring an optimal path discovery process.
24+
25+
6. `astar(start, end, obstacles)`: With a fusion of Dijkstra's algorithm and heuristic estimation, `astar()` undertakes the challenge of finding the shortest path on the grid.
26+
By employing a priority queue based on the sum of current cost and heuristic, it efficiently navigates the grid while factoring in the estimated distance to the goal.
27+
28+
7. `dfs(start, end, obstacles)`: This function embarks on a journey through the grid using Depth-First Search (DFS). It bravely traverses as far as possible along each branch,
29+
backtracking only when faced with a dead-end, ultimately discovering the end node or exhaustively exploring all feasible paths.
30+
31+
8. `bfs(start, end, obstacles)`: Embodying the essence of Breadth-First Search (BFS), this function systematically explores the grid level by level,
32+
emanating from the start node. Its steadfast approach guarantees the discovery of the shortest path upon reaching the end node, making it an ideal candidate for optimal solutions.
33+
34+
9. `heuristic(point, goal)`: As the backbone of A* algorithm's guidance system, this function calculates a heuristic value critical for navigating towards the goal node.
35+
Through the meticulous computation of the Manhattan distance between the current point and the goal, it provides a valuable estimate of the remaining distance to the goal.
36+
37+
10. `neighbors(cell)`: Acting as the gatekeeper to the grid, `neighbors()` identifies the valid neighboring cells for a given cell.
38+
By meticulously considering adjacent cells in the four cardinal directions, it ensures the algorithm's exploration remains confined within the boundaries of the grid.
39+
40+
11. `remove_obstacle(cell, obstacles)`: When obstacles need to be vanquished from the grid, this function steps up to the challenge.
41+
It orchestrates the removal of the obstacle from the set of obstacles, meticulously clearing the cell by redrawing it with a black color, and meticulously updating the surrounding grid lines to conceal the erstwhile obstacle.
42+
43+
12. `generate_random_maze(obstacles)`: Infusing a dash of unpredictability into the grid, this function breathes life into a maze with obstacles.
44+
It meticulously traverses each cell in the grid, making calculated random decisions on whether to add an obstacle, ultimately sculpting a maze-like structure that puts the algorithms to the test.
45+
46+
13. `create_menu()`: This function serves as the gateway to user interaction, crafting a visually appealing menu interface using Tkinter.
47+
It empowers users to choose their preferred algorithm and fine-tune visualization settings, providing a seamless and intuitive means to interact with the program.
48+
49+
14. `run_algorithm(selected_algorithm, create_maze)`: As the conductor orchestrating the symphony of algorithms,
50+
this function takes charge of executing the selected algorithm. It adeptly manages user inputs, sets the stage for algorithmic exploration, and navigates the execution process, ensuring a fluid and immersive user experience.
51+
52+
15. `main()`: Serving as the cornerstone of the program's architecture, `main()` lays the foundation for user interaction.
53+
By initializing the menu interface through `create_menu()`, it ignites the spark of user engagement, inviting them to embark on a journey of algorithmic exploration and visualization on the grid.
54+
55+
Learned a new word "meticulous" recently
11256
Note: Make sure to have the Pygame library installed (pip install pygame) before running this script.
11357
PS: I plan on adding new algos and some new functions(maze generation, grid resizing etc) that may change or make my previous codes/descs obsolete.
11458
(I want a new GUI pls help)

0 commit comments

Comments
 (0)