Search Algorithm Playground is a python package to work with graph related algorithm, mainly dealing with different Artificial Intelligence Search algorithms. The tool provides an user interface to work with the graphs and visualise the effect of algorithm on the graph while giving the freedom to programmer to make adjustments in the way they wants. It also provides a way to save the graph in json format hence enabling the programmers to share the files and use different algorithm on same graph with ease.
The package is made using pygame module.
Currently supports only undirected graphs
pip install SearchAlgoPlayground
Copy the repository in your system then do
python setup.py install
You can also copy/paste the SearchAlgoPlayground folder into your project
Double click on any empty block will create a node on it.
NOTE: Single click highlights the selected block and info label area will display it's location in 2D Matrix.
Clicking on a node single time selects the node for creating an edge with that.
Select one node, once selected select another node to create an edge between them.
Double click on any element makes it go in modify mode which allows the element to be deleted or edited.
To delete an edge double click on it and then press DELETE
To edit an edge weight double click and use keyboard to modify it's value, once done hit ENTER or click anywhere else.
To delete a node double click on it and then hit DELETE on keyboard
To edit node label double click on a node and use keyboard to modify the label, once done hit ENTER or click anywhere else.
NOTE: Label of a node must be unique
Click on the node and drag it on the playground.
- simple PlayGround
- Loading graph from file
- Set filename to save your work into
- PlayGround with weighted edge
- Setting up dimension for the world in playground
- Setting onStart event
- Changing configuration for playground
- Working with neighbouring nodes
Creates PlayGround object with default values
from SearchAlgoPlayground import PlayGround
pg = PlayGround() #Creating a playground object
pg.run() #run the playground
Method Used: fromfilename()
NOTE: The graph file here in below example Graph.json must have been saved by the playground, i.e. saved by clicking Save Work button.
from SearchAlgoPlayground import PlayGround
pg = PlayGround.fromfilename("Graph.json") #loading a playground from a file
pg.run() #run the playground
Parameter used: saveToFile
from SearchAlgoPlayground import PlayGround
pg = PlayGround(saveToFile = "MyWork.json") #Creating a playground object with name of the file provided where the work will be saved
pg.run() #run the playground
Parameter used: weighted
from SearchAlgoPlayground import PlayGround
pg = PlayGround(weighted=True) #Weighted playground
pg.run() #run the playground
Parameter used: saveToFile, weighted, block_dimensions
from SearchAlgoPlayground import PlayGround
#A weighted playground with a name of the file where work need to be saved given as MyWork.json
#block_dimension is dimension of 2D matrix (rows,cols) here both are 20
pg = PlayGround(saveToFile = "MyWork.json",weighted=True,blocks_dimension=(20,20))
pg.run() #run the playground
Method set as onStart will be executed once the Start button is clicked shown on playground.
Parameter used: saveToFile, weighted, block_dimensions
Method used: onStart()
from SearchAlgoPlayground import PlayGround
#A weighted playground with a name of the file where work need to be saved given as MyWork.json
#block_dimension is dimension of 2D matrix (rows,cols) here both are 20
pg = PlayGround(saveToFile = "MyWork.json",weighted=True,blocks_dimension=(20,20))
##Sample function to be put as start for playground
def sayHello():
print("Hello From Playground!")
pg.onStart(sayHello) #Setting method for on start click
pg.run() #run the playground
Changing values in configuration can modify the default values for PlayGround and world related to it.
from SearchAlgoPlayground import PlayGround
from SearchAlgoPlayground import config
from SearchAlgoPlayground.config import YELLOW,PURPLE
config["BACKGROUND_COLOR"] = YELLOW #set background color as yellow
config["NODE_COLOR"] = PURPLE #set node color as purple
#A weighted playground with a name of the file where work need to be saved given as MyWork.json
#block_dimension is dimension of 2D matrix (rows,cols) here both are 20
pg = PlayGround(saveToFile = "MyWork.json",weighted=True,blocks_dimension=(20,20))
pg.run() #run the playground
Below are the given default values, or look into the file config.py
config = {
"TITLE":"Algo PlayGround", #Title of the playground window
"BLOCKS_DIMENSION":(21,23), #ROWS,COLUMNS
"BLOCK_SIZE":30, #Size of each block i.e. sides
"BOTTOM_PANEL_HEIGHT":200, #Size of bottom panel for control
"MARGIN":15, #Margin between sides and the grid
"GRID_WIDTH":1, #Width of the boundary of the block
"BACKGROUND_COLOR":WHITE, #Color of the background of the world
"GRID_COLOR":GRAY, #Block boundary color
"HIGHLIGHT_COLOR":DARK_GRAY, #Highlighting color
"BUTTON_COLOR_PRIMARY":BROWN, #Color for the button larger
"BUTTON_COLOR_SECONDARY": PURPLE, #color for the smaller button
"INFO_LABEL_COLOR":DARK_GRAY, #color for the info text
"NODE_COLOR":GRAY, #color of the node
"NODE_BORDER_COLOR":BLACK, #color of the border of node
"SPECIAL_NODE_BORDER_COLOR": DARK_PURPLE,#Special node border color
"SPECIAL_NODE_COLOR":GREEN, #special node color
"SELECTED_NODE_COLOR" : RED, #color of the node selected
"ELEMENT_ACTIVE_COLOR":BLUE, #Element selected by user is considered as active to the playground
"MY_WORK_DIR": "MyGraph/" #Directory in which the work is saved
}
Parameter used: saveToFile, weighted, block_dimensions
Method used: onStart(), getStartNode(), MoveGen(), get_edge(),get_weight(), get_label()
from SearchAlgoPlayground import PlayGround
#A weighted playground with a name of the file where work need to be saved given as MyWork.json
#block_dimension is dimension of 2D matrix (rows,cols) here both are 20
pg = PlayGround(saveToFile = "MyWork.json",weighted=True,blocks_dimension=(20,20))
#Function prints all the neighbouring nodes of the start node in the playground and the weight of the edge connecteding them
def printNeighbours():
S = pg.getStartNode() #get start node from playground
#MoveGen method returns the neighbouring nodes
neighbours = pg.MoveGen(S) #Generating the neighbouring nodes
#print details of the node
for node in neighbours:
#get weight of the edge between S and node
edge = pg.get_edge(S,node) #method will return Edge class object
weight = edge.get_weight() #method in Edge class will return weight of the edge
#Display the details
print("Edge: {} - {}, Weight: {}".format(S.get_label(),node.get_label(),weight))
pg.onStart(printNeighbours) #Setting method for on start click
pg.run() #run the playground
Above prints value for the following graph
Edge: S - A, Weight: 17
Edge: S - B, Weight: 34
Edge: S - C, Weight: 10
Check more implemented examples here.
PlayGround class represents the ground which which consists of the world of blocks on which the graph is displayed or modified. PlayGround class provide controls on the elements in the world like Edge and Nodes.
world, saveToFile, weighted, startNode, goalNode, block_dimensions, block_size
A World class object on which the nodes/edges are drawn The screen size of the world determines the screensize of the playground window (default None).
name of the file with which the world(or graph) will be saved(file will be saved in json format) when the 'Save Work' button is pressed (default None).
whether the edges that will be drawn on playround is weighted or not (default False).
a node object of Node class which will be set as start node for the graph. if no value is provided then top left block contains the start node 'S'
NOTE: startNode is a special node which cannot be deleted from the playground(default None)
a node object of Node class which will be set as start node for the graph. if no value is provided then bottom right block contains the goal node 'G'
NOTE: goalNode is a special node which cannot be deleted from the playground(default None)
blocks_dimension represents number of blocks that will be generated in the world if world object is given as None(default (23,21))
e.g (23,21) represents 23 rows and 21 columns
size of each block i.e. one side of the squared block (default 30)
World class object on which playground is available
fromfilename(), addUIElement(), removeUIElement(), onStart(), delay(),getAllNodes(),getAllEges(), MoveGen(), get_edge(), getGoalNode(), getStartNode(), setGoalNode(), setStartNode(), getScreen(), add_node(), add_edge(), remove_edge(), remove_node(), saveWork(), showInfoText(),get_dimension(), to_dict()
a classmethod which returns PlayGround class object initialised from values given in filename and returns the object
filename: a json file name to which previously a playround is saved into
Adds UI element to the playground
NOTE: any UI element must contain draw() method which takes pygame screen as a parameter, the method will be called each time frame is drawn
Removes UI element from the playground
Sets function to be executed when the start button is clicked
func: function which will be executed when start is pressed
Delays the program for given milliseconds
Uses pygame.time.delay method
Once the controls are taken away no other control would work on playground except exit
NOTE: Using this delay function would allow to reflect changes on playground in delay mode better than instantaneous
Returns all the neighbours(in sorted order according to the label) of a node i.e. all the nodes which has edge between the given node
node: A Node class object
Returns an Edge class object between the node nodeStart and nodeEnd, if no edge exists returns None nodeStart: A Node class object
nodeEnd: A Node class object
Returns all nodes available in the world as a list
Returns list of all edges available in world
Returns Node class object which is currenty set as a goal node for the playground
Returns Node class object which is currenty set as a start node for the playground
Sets the given node as goal node for the PlayGround node: A Node class object
Sets the given node as goal node for the PlayGround
node: A Node class object
Returns a pygame window object which is the surface on which the elements are being drawn
Useful in case more extra elements are needed to be drawn on the playground
Adds node to the world
NOTE: node available in the world will be displayed on the playground screen
Adds edge to the world
NOTE: edge available in the world will be displayed on the playground screen
Removes edge from the world
Removed node from the world
Saves the playground with the given filename. if no filename is provided, then playground will be saved with arbitrary filename
To display informational texts on the playground right above the start button
text: text to be displayed on the playground infoText area
Returns Playrgound attributes as dictionary
Sets the title of the playground window
title: a string value
runs the playground as an active window on which the frames are drawn
A World class represents the world for the playground which is responsible for Maintaining Node,Edge and Block of the playground
blocks_dimension, block_size, bottom_panel_size, grid_width, background_color, gird_color, margin
blocks_dimension represents number of blocks that will be generated in the world e.g (23,21) represents 23 rows and 21 columns
size of each block i.e. one side of the squared block
height of the bottom panel on which buttons and other UI element will be drawn min allowed 180
Width of the grids
A rgb value type of the form (r,g,b) to set color for the background of the world default (255,255,255)
A rgb value type of the form (r,g,b) to set color for the blocks border of the world default (232, 232, 232)
Margin from the edges of the playground window, minimum value allowed is 10, default 10
fromdict(), create_grids(), add_node(), remove_node(), update_node_loc(), getEdges(), add_edge(), remove_edge(), getNodes(), getNode(), getBlock(), get_dimension(), to_dict()
A classmethod to create World class object from a dictionary
NOTE:The dictionary must be of the same form returned by to_dict() method of the class
Generates grids if not generated in the world, if the gird is already availbale then it redraws them
Adds nodes to the world
NOTE: To make the node visible on playground window it must be include in the world
Removes nodes from the world
NOTE: If nodes are not available in the world it will no longer visible on playground window
Updates the location of the node to newBlock location and removes it from previous block. node:Node - A Node class object which needs to be updated newBlock:Block - A Block class object to which the node is require to move to
Returns all the available edges in the world as dictionary with key as the node pairs ids e.g ((1,1),(1,5)) is the key for an edge between the node with id (1,1) and (1,5)
NOTE: The id represents position in the 2D matrix of the block
Adds edge to the world, edge added to the world will be visible on Playground window
NOTE: Edges are added with the key of the end node ids e.g. ((1,1),(1,5)) is the key for an edge between the node with id (1,1) and (1,5)
Removes the edge from the world. The edge removed from the world will no longer be visible on the Playground window
Returns edge between startNodeID and endNodeID if there exists an edge else returns None startNodeID:tuple - id of the node which has edge with the other node we're looking for endNodeID:tuple - id of the node which has edge with the other node we're looking for
Returns the dictionary of all the nodes available in the world Key of is the id of the node
Returns node with given key, returns None if the node doesn't exists _key:tuple _- id of the node we are looking for, location in the grid or 2D array.
Returns block at the given id. id:tuple - Index Location in 2D matrix
Returns dimension of the world as tuple of (rows,col)
returns the object details with all attribute and values as dictionary
Block defines the world tiles. Blocks represents the world in 2-Dimensional array format.
x coordinate in the window plane of the block
y coordinate in the window plane of the block
size of the block, denotes one side of the square block
id represents position in the 2D matrix of the block (x,y) where x is the row and y is the column
pygame rect object
x, y, size, id, gird_color, grid_width
x coordinate in the window plane of the block
y coordinate in the window plane of the block
size of the block, denotes one side of the square block
id represents position in the 2D matrix of the block (x,y) where x is the row and y is the column
rgb color (r,g,b) value for the block boundary default ((163, 175, 204))
width of the boundary default 1
draw_block(), highlight(), pos(), setHasNode(), hasNode(), to_dict()
draws the block on pygame window screen: pygame window
highlights block with highlist color val:bool - true to enable highlight
returns the coordinate of the centre of the block on the pygame window
sets the value for the flag _hasNode to represent that a block contains a node
returns true if block has node over it
returns the object details with all attribute and values as dictionary
A node is a type of block that is important to the world Node class inherits the Block class.
block, label, colorOutline, colorNode, outlineWidth, specialNodeStatus
A Block class object on which the node will be drawn
Label of the node
A rgb value of the form (r,g,b) represents outline color of the node
A rgb value of the form (r,g,b) represents color of the node
Width of the outline of the node default 2
sets whether the node is special default is False
NOTE: A special node must be present on playground all time, i.e. delete is not allowed
x coordinate in the window plane of the block
y coordinate in the window plane of the block
size of the block, denotes one side of the square block
id represents position in the 2D matrix of the block (x,y) where x is the row and y is the column
pygame rect object
coordinate in pygame window for center of the node
draw_block(), highlight(), pos(), setHasNode(), hasNode(), to_dict(), set_label(), selected(), set_color(), get_label(), setLocation(), handle_event(), add_neighbour(), remove_neighbour(), get_neighbours()
draws the node on pygame window screen: pygame window
highlights block with highlist color val:bool - true to enable highlight
returns the coordinate of the centre of the block on the pygame window
sets the value for the flag _hasNode to represent that a block contains a node
returns true if block has node over it
returns the object details with all attribute and values as dictionary
sets the label on the node screen - a pygame window
label:str - a string value that'll be displayed on node
sets isSelected flag value
sets the color of the node
color:tuple - A rgb value in the form (r,g,b)
returns value of label of the node
sets the location to the new block block:Block - A Block class object
NOTE: Location for nodes are defined by the block they resides on
Internal method to handle the pygame events
Adds the given node as neighbouring node if it's not already a neighbouring node, should be used when it has an edge with the given node
node:Node - A Node class object
Removes the given node from neighbouring node if it's in neighbouring node node:Node - A Node class object
Returns list of neighbouring nodes(Node class objects) which is sorted in order with their label
An edge class represents an edge between 2 nodes
nodeStart, nodeEnd, isWeighted, weight, edgeColor, edgeWidth,
A Node class object which represents the starting node of the edge
A Node class object which represents the ending node of the edge
Whether the edge drawn between the node has weight or not, default False
Wieght of the edge, default 0
A rgb value of the form (r,g,b) which represents the color of the edge, default value NODE_BORDER_COLOR
Width of the edge, default 3
A pygame rect object
handle_event(), set_color(), collidePoint(), draw_edge(), getNodes(), get_weight(), to_dict()
Internal method to handle the pygame events
Sets color of the edge color:tuple - A rgb value of the form (r,g,b)
Returns true if the given click point is inside the offset value on edge
Draws edge on the screen screen - A pygame window
Returns the pair of node which the edge is connecting
Returns the weight of the edge
Returns the object details its attributes and value as dictionary
Label to add on pygame screens
Draws the label on the pygame screen screen: pygame screen
Set the value for label
color of the label in (r,g,b) format
size of the label
(x,y) coordinates for the position of label
Button elements for pygame screen
draws button element on pygame screen screen: pygame window
Returns true if pos is a collidePos for the pygame rect element
pos, size, bgColor, color, label, labelSize, fill_value,
(x,y) coordinates for the position of button
(width,height) of the button
background color for the button
color of the button label
label of the button
size of the label
fill value for pygame rect