5 Easy steps for beginners to make animation of sorting algorithms using Pygame

Hi guys...
So if you are seeing this article that means you are ready to make your animations of sorting algos.

Alright so we can start without wasting the time.

So We are going to use Python language to make these animation...

What?? what are you talking about .I don't know anything about  python. how am i supposed to make animations now...

Chill..relax..?? When i made these myself i was also a beginner but it doesn't change the fact i wanted to make one of  these animation. So i started and guess what? there is nothing to fear about python its just a language not actually a python(tell me you got my poor pun).

You just believe in yourself and start ,its easier then it sounds.

Alright below are some steps of how you can get started..(crack your knuckles you are going to be awesome):

STEP:1- Installing the prerequisites:

first you need to install python on your system . you can do it by going to below link and choosing a package depending on your system property.

Download Python from here

Now you need to install pygame for your system.( And what is this now, first python now pygame,what is going on........Calmdown guys it's just a library like we use in any languages..remember "#include" something like that.)

You can download the latest version.Use this link to download.

or you can also use windows command line do it it the hacker way...
just type   pip install pygame    in command window .It should automatically download pygame on your system.

Well you are all set for doing some awesome work.

STEP:2- Setting up your text editor:

As the name suggests it is where you are going to change text.
well there are many option for choosing a text editor,we can work just fine with the one that python provides. It's called "Python IDLE".

So go to your windows search and serch the keyword 'IDLE'
1-Now open IDLE.
2-go to files and select new File.

Now we are in editing mode.
now write the below codes on starting of your new file
import pygame
from pygame import *
It is basically importing that pygme library so that you can use it in your file. Just the like "#include< >" thing in other languages.

Now save the file.( i am saving as 'sorting.py') you can choose anyname just make sure it has '.py' at end.
Now click the run menu on top and select "Run Module".

Now your python shell will open with a restart written in middle and after that some '>' signs just like this
=======RESTART:C:/Users/Username/Desktop/sorting.py======
>>>
if you get this then you are set to start editing the real code from here .So close the shell and go on your file(in my case 'sorting.py')

Note: if you get any error saying " import error:No module name 'pygame' found " or anything like this then your pygame library is not installed correctly . go back to step:1 and try to install it again.

STEP:3- Creating a screen to show animation:

first we need to initialize the imported pygame library .so type-
pygame.init()
First we should decide how big screen we want.we can do this by. then we can pass the screen size in built in function to create screen(or screen object ) of that size.
scr_size = (width,height) = (1000,700)
screen = pygame.display.set_mode(scr_size)
Now if you save and run this file you should see a black window popping out of your defined size with window name "pygame window".but if you try to close it ,it doesn't respond. That's because we didn't tell our program to react when we click on close icon.
Now type this-
pygame.quit()
quit()
the first line above un-initialize the pygame library which we initialized at top, and the second line closes the pygame window.
Now when you run the program the screen pops and closes.Because we just write the code to close without any condition. so lets add a condition. for that we need to create a loop which wiil run till the condition the arrives for that-(put the above two lines at very last of code)
NOTE:Indentation in python is very crucial.
Exit = False
while not Exit:
 for event in pygame.event.get():
  if event.type == pygame.QUIT:
   Exit = True
Exit is a variable that is 'False' initially it would be changed to 'True ' when condition arrives.
now while loop starts.it run till "not Exit" is True that is "Exit" is False.Then we are checking for any event (any key press ,mouse movement,mouse click etc.) and if the event is of type "pygame.QUIT" (that is clicking on close icon) then we toggle the value of "Exit" to True. So the loop breaks and now we will reach to the last code of our program that was related to quit and thus program will close.

STEP:4- Creating a random array and displaying it -

(write every code of this step above "Exit "  variable )

random function is available in python in "Random" library so import this library at top with others
import random
now your array object will be-
n=50
start =1
end = 500
def randArray(n ,start ,end):
 arr = [ ]
    for i in range(n):
  arr.append(random.randint(start,end))
 return arr
 
arr = randArray(n,start,end)
It will create an array of 50 elements with random integers between 1 to 500.

Now we will define a function to display this array on screen.
clock = pygame.time.Clock()
FPS = 20
green = (0,255,0)
black = (0,0,0)
barWidth = int(9*width/(20*n))
graph_start = int(width/20)

def dispArray(arr):
    screen.fill(black)
    for i in range(n):
        pygame.draw.rect(screen ,green ,[graph_start+i*2*barWidth,height-100,barWidth ,-arr[i]])
    pygame.display.update()
    clock.tick(FPS)
The first line creates a clock object( basically  to deal with how fast or slow your animation will be).
FPS is variable for frames per second. green/black defines green/black color and in RGB format.
barWidth is width of one value in your array
graph_start is the point from where array plotting starts on screen.
Then the function fills screen with black each time and then draws each element of array on screen object with green color. X- plot starts according to graph_start.
height-100 defines the Y-plot starts 100 pixels above the bottom of screen. and  -arr[i] defines that the height of plot is equal to value of arr[i]( the negative sign is because we measure y from top to bottom as positive Y-axis)
Now call this function in exit loop-
dispArray(arr)
Now save your file and hit run.
your screen should look like this-

Feeling good .that's the spirit hop over to next step.

Step:5- making the animation -

Now choose a sorting algorithm to animate.(in my case i am choosing Selection sort here)
def selectionSort(arr):
    for i in range(n):
        min_ind = i
        for j in range(i+1,n):
            if arr[min_ind] > arr[j]:
                min_ind = j
        arr[i],arr[min_ind] = arr[min_ind],arr[i]
        dispArray(arr)
This function defines selection sort( you can find different sorting algorithms code online or you could use your own). And the last line of every iteration it calls the "dispArray" function which fills the screen with black and then redraw the new values of array.
Now in the exit loop where we called dispArray, replace    dispArray(arr)   with this code-
if sorted(arr) != arr:
    selectionSort(arr)
else:
    dispArray(arr)

sorted is inbuilt function of python for sorting. so when the loop runs it checks if array is sorted or not if not then call selection sort otherwise just display the array as it is.The final code should look like below :
import pygame
from pygame import *
import random

pygame.init()

#creating screen object
scr_size = (width,height) = (1000,700)
screen = pygame.display.set_mode(scr_size)
pygame.display.update()

#creating random array
n=50
start =1
end = 500
def randArray(n ,start ,end):
    arr = []
    for i in range(n):
        arr.append(random.randint(start,end))
    return arr
arr = randArray(n,start,end)

#function to display array
clock = pygame.time.Clock()
FPS = 20
green = (0,255,0)
black = (0,0,0)
barWidth = int(9*width/(20*n))
graph_start = int(width/20)
def dispArray(arr):
    screen.fill(black)
    for i in range(n):
        pygame.draw.rect(screen,green ,[graph_start+i*2*barWidth,height-100,barWidth,-arr[i]])
    pygame.display.update()
    clock.tick(FPS)

def selectionSort(arr):
    for i in range(n):
        min_ind = i
        for j in range(i+1,n):
            if arr[min_ind] > arr[j]:
                min_ind = j
              
        arr[i],arr[min_ind] = arr[min_ind],arr[i]
        dispArray(arr)
    
#creating loop and exit condition
Exit = False
while not Exit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            Exit = True
    if sorted(arr) != arr:
        selectionSort(arr)
    else:
        dispArray(arr)
            
pygame.quit()
quit()
Now hit save and run and you can see your code working.
Now you can tweak with different values of  n, FPS ,colors , bar_width ,graph_start etc

Go and make animation for every sorting algorithm you know.
Now it seems pretty easy huh!!

PEACE !!!

Follow my facebook page to get updated with new content : www.facebook.com/TheCreatricks/

Comments

  1. Its awesome i made my first ever animation and its working, thanks

    ReplyDelete
  2. Great tutorial for beginners. Simple to understand and quite helpful

    ReplyDelete

Post a Comment

Popular posts from this blog

Convert your Python file to executable windows file

Animation of Sorting Algorithms