It has become appallingly obvious that our technology has exceeded our humanity

The era of Computer Buisness!!!

Wednesday, 25 December 2013

MONSTER SWEEP

This is my first GUI game code. This is a mere luck based game where you have to click on any of the 25 blocks given on the screen to open it. You can continue your game till you click on a monster containing box. Once you click on the monster containing box.. YOU DIE!! GAME OVER!!
This is purely codded in python language, inspired from the traditional minesweeper game with a little bit change in the game logic.
This is the code but might not properly work because it uses some image files. Unfortunately i don't know how to upload a file into a blog!

#***************************************************************************#
#        Author: Chaythanya SK                                                                                                 #
#        Name of project: MONSTER SWEEP GAME                                                             #
#        RULES: open the boxes containing numbers only if you open the monster           containing box.. you die!! GAMEOVER!                                                                          
#            mere luck based game                                                                                              #
***************************************************************************


import pygame
import random
# declaring colours
black=(0,0,0)
white=(255,255,255)
green=(1,255,0)
yellow=(15,100,0)
red=(255,0,0)
blue=(19,37,173)
orange=(240,69,12)
pygame.init()
size=[375,300]                  # size of the game window
screen=pygame.display.set_mode(size)   
pygame.display.set_caption('MONSTER SWEEP')    # title of the game window
done=False
smile=pygame.image.load("smiley.jpeg").convert()    #getting images
index=pygame.image.load("index.jpeg").convert()        #getting images

clock=pygame.time.Clock()
screen.fill(white)       
r1=[]
r2=[]
r3=[]
r4=[]
r5=[]
grid=[r1,r2,r3,r4,r5]        # game array
minecount=0   
remaining_no=0
GI=-1                # row to be selected initialised as -1
GJ=-1                # col to be selected initialised as -1
open_count=0            # no of boxes opened
def make():            #making the first look
    cord_y=0+50
    cord_x=0
    screen.fill(white)   
    for i in range(5):
        for j in range(5):
            pygame.draw.rect(screen,black,[cord_x,cord_y,75,50],2)        # draw the grid
            cord_x=cord_x+75
        cord_x=0
        cord_y=cord_y+50
    pygame.display.flip()            #update the screen
    assign(grid)
   
def assign(grid):        # assign monsters and numbers in the grid
    global minecount
    global remaining_no
    for i in range(5):                #fill the grid with random nos
            for j in range(5):
                    grid[i].append(random.randrange(0,5))

    for b in range(10):                # put "bomb"(monsters) in some random places
        temp1=random.randrange(0,5)
        temp2=random.randrange(0,4)
        grid[temp1][temp2]='bomb'
    for i in range(5):
            for j in range(5):
                    if grid[i][j]=='bomb':
                            minecount=minecount+1        #count the no: of monsters
    remaining_no=25-minecount                #count the remaining boxes
    font=pygame.font.Font(None,25)
        text=font.render("monster count:"+str(minecount),True,black)    #blit the monster count in the screen
        screen.blit(text,[20,17])
    pygame.display.flip()            # update the screen

def checkbomb(x,y):                #identify the selected box.. x,y are the coordinates of mouse click
    global grid
    global open_count
    global temp_remaining_nos
    open_count=open_count+1            #box opened
    block_no=0
    selected_no=0
    flag=0
    lcord_x=0                # left x coordinate
    ucord_y=50                # up y coordinate
    dcord_y=100                # down y coordinate
    rcord_x=75                # right x coordinate
    for i in range(5):           
        for j in range(5):
            block_no=block_no+1
            if(x>lcord_x and x<rcord_x and y>ucord_y and y<dcord_y ):# find the selected box no (1-25)
                selected_no=block_no
                flag=1
                break
           
            lcord_x=lcord_x+75
            rcord_x=rcord_x+75
       
        if(flag==1):
            break
        lcord_x=0
        rcord_x=75
        ucord_y=ucord_y+50
        dcord_y=dcord_y+50
    find_grid_pos(selected_no)         # find row and col of the selected block no (1-25)
    grid_display(x,y,lcord_x,rcord_x,ucord_y,dcord_y)
def find_grid_pos(selected_no):        #find the row and col of the selected block no (1-25)
    global GI
    global GJ
    if selected_no==1:
        GI=0
        GJ=0
    if selected_no==2:
                GI=0
                GJ=1
    if selected_no==3:
                GI=0
                GJ=2
    if selected_no==4:
                GI=0
                GJ=3
    if selected_no==5:
                GI=0
                GJ=4
    if selected_no==6:
                GI=1
                GJ=0
    if selected_no==7:
                GI=1
                GJ=1
    if selected_no==8:
                GI=1
                GJ=2
    if selected_no==9:
                GI=1
                GJ=3
    if selected_no==10:
                GI=1
                GJ=4
    if selected_no==11:
                GI=2
                GJ=0
    if selected_no==12:
                GI=2
                GJ=1
    if selected_no==13:
                GI=2
                GJ=2
    if selected_no==14:
                GI=2
                GJ=3
    if selected_no==15:
                GI=2
                GJ=4
    if selected_no==16:
                GI=3
                GJ=0
    if selected_no==17:
                GI=3
                GJ=1
    if selected_no==18:
                GI=3
                GJ=2
    if selected_no==19:
                GI=3
                GJ=3
    if selected_no==20:
                GI=3
                GJ=4
    if selected_no==21:
                GI=4
                GJ=0
    if selected_no==22:
                GI=4
                GJ=1
    if selected_no==23:
                GI=4
                GJ=2
    if selected_no==24:
                GI=4
                GJ=3
    if selected_no==25:
                GI=4
                GJ=4

   
   

def grid_display(x,y,lcord_x,rcord_x,ucord_y,dcord_y): # display the content of the opened box
    global GI
    global GJ
    global grid
    #print grid
    font=pygame.font.Font(None,25)
    if(str(grid[GI][GJ])=='bomb'and open_count>=1): # if the opened box contains bomb show game over
        showgrid_gameover()            # diaply whole grid
    else:                        # else display the no:   
        text=font.render(str(grid[GI][GJ]),True,black)
        screen.blit(text,[lcord_x+30,ucord_y+15])
        if (open_count==remaining_no+1):        #if open count equals remining no you win!
            showgrid_win()            #display whole grid
    pygame.display.flip()                # update screen to show no:
def showgrid_gameover():                # show game over screen
    global grid
    x_cord=0
    y_cord=50
    for i in range(5):
        for j in range(5):
            if (grid[i][j]=='bomb'):
                screen.blit(index,[x_cord+20,y_cord+5])
            else:
                font=pygame.font.Font(None,25)
                text=font.render(str(grid[i][j]),True,black)
                screen.blit(text,[x_cord+30,y_cord+15])
           
            x_cord=x_cord+75
        x_cord=0
        y_cord=y_cord+50
    pygame.draw.rect(screen,white,[0,0,375,50])

    screen.blit(smile,[170,7])
        font=pygame.font.Font(None,25)
        text=font.render("press me--->",True,black)    # show press me smiley to restart game
        screen.blit(text,[55,17])
    font=pygame.font.Font(None,55)
    text=font.render("GAME OVER!!!",True,blue)
    screen.blit(text,[80,150])
        pygame.display.flip()
           
def showgrid_win():            # show "you won" screen
    global grid
        x_cord=0
        y_cord=50
        for i in range(5):
                for j in range(5):
                        if (grid[i][j]=='bomb'):
                                screen.blit(index,[x_cord+20,y_cord+5])
                        else:
                                font=pygame.font.Font(None,25)
                                text=font.render(str(grid[i][j]),True,black)
                                screen.blit(text,[x_cord+30,y_cord+15])

                        x_cord=x_cord+75
                x_cord=0
                y_cord=y_cord+50
    pygame.draw.rect(screen,white,[0,0,375,50])
           screen.blit(smile,[170,7])
        font=pygame.font.Font(None,25)
        text=font.render("press me--->",True,black)        # show press me smiley to restart the game
        screen.blit(text,[55,17])
    font=pygame.font.Font(None,50)
        text=font.render("BRAVO YOU WIN!!!",True,blue)
        screen.blit(text,[60,150])

def check_reset(x,y):            # check if the press me smiley is pressed
    global r1
        global r2
        global r3
        global r4
        global r5
        global grid
    global minecount
    global remaining_no
    global GI
    global GJ
    global open_count
    if(x>=170 and x<=210 and y>=7 and y<=47):    # trace the coordinates
        r1=[]                    # reinitialise everything
               r2=[]
            r3=[]
                r4=[]
               r5=[]
              grid=[r1,r2,r3,r4,r5]
        minecount=0
        remaining_no=0
        GI=-1
        GJ=-1
        open_count=0
        temp_remaining_nos=0
        screen.fill(white)
        make()                # make the screen again



make()
while done==False:
    clock.tick(20)
    for event in pygame.event.get():    # for each thing you do in the screen
       
        if event.type==pygame.QUIT:    # if it is quit exit the loop
            done=True
        elif(event.type==pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0]): # if the mouse is pressed
            x,y=pygame.mouse.get_pos()        # get the position
            check_reset(x,y)            # check if the reset button is pressed
            checkbomb(x,y)                # check for the bomb
       
    pygame.display.flip()                    # update the screen
pygame.quit()                            # quit the game
   















































Sunday, 10 November 2013

Google God??

Ever thought about the "Google" as a god?
Google technology has advanced so much that today it referred to provide a god like service.Today Google has become much more than a mere search engine. In fact "google" is nowadays commonly used as a verb, probably it is the most common thing which all of us indulge in.

Search Engines in the limelight

A search engine is defined as “a program for the retrieval of data, files, or documents from a database or network.”  The most common type of search engines was developed to search, what we term, the Internet.  Though within academic and other databases, such as Ebsco, there are search engines to search the content within the database holdings.  You may be familiar with Westlaw and LexisNexis; they both have internal search engine programs that search the content behind the password wall.
I used a search engine to help me find the above-mentioned definition.  I used Google.  That is my search engine of choice.  However, there are a quite a few other well-known search engines, such as Dogpile, Yahoo!, or Bing.  Did you know that there were over 150 different types of search engines available to search for web content?  So rather than looking at one particular search engine as a one-stop-shop location for all resources available online, you might consider choosing your search engine, or engines, by what type of resources you are looking to review.  There are two ways to evaluate search engines:
(1) by content, meaning what they are searching, and
(2) by how the information is compiled that they are searching, meaning that you are searching within a directory versus an index.
Search engines can be broken down into different categories of expertise for searching.   You might consider the following categories in determine what you’re looking for in your search: Blog Search Engines; Book Search Engines; Business Search Engines; Forum Search Engines; Image and Multimedia Search Engines; International Search Engines; Job Search Engines; Legal and Law Enforcement Search Engines; Map Search Engines; Medical Search Engines; News Search Engines; People Search Engines; Price/Shopping Search Engines; and Social Search Engines.[i]  Specific search engines may be better suited for one type of search over another.  For example, if you were looking for someone’s phone number, you might want to use a people search engine versus a social media search engine, which would give you any Facebook, Twitter, MySpace information over actual phone numbers and addresses.
Another factor in considering which search engine you want to use is to evaluate how that search engine searches for information.  You might consider whether the search engine is human-powered directory, searching the invisible or deep web, or is an all-purpose crawler search engine.  Here are the differences.  Human-powered search engines are also known as web directories, which is an index that is compiled by humans.  Humans add links that they determine to be high quality to a directory, and when you run a search using this human-driven search engine, you are searching that directory of links for information relevant to your query.  The following list includes human-based search engines:
  • Mahalo (Web directory that uses human editors and displays the results beside a Google search)
  • Eurekster Swickis (Web directory that you create and have complete control over. Still in Beta form).
  • Open Directory ( The “largest, most comprehensive human-edited directory of the Web. It is constructed and maintained by a vast, global community of volunteer editors.”[ii] The Open Directory project is also known as DMOZ, or Directory Mozilla.)
  • Yahoo!Search Directory (“The Yahoo Directory is a human-created and maintained library of web sites organized into categories and subcategories. Yahoo editors review these sites for potential inclusion in the Directory, and to evaluate the best place to list them.”[iii])
All-purpose search engines that use crawlers, such as Google, search information a bit differently.  Rather than having humans add information and links to an index, a company, such as Google, runs a program (also known as a spider) that follows links throughout the Internet.  While it is following, or crawling, through the web, the program is grabbing information from websites and adding it to an index. Additionally, “the crawler doesn’t rank the pages, it only goes out and gets copies which it stores, or forwards to the search engine to later index and rank according to various aspects.”[iv]















With a sea of information all around Google is the " fish net" that finds you exactly what you need. Better call it god!

First animation code in Python

One of the best online tutorial to get started with Coding games in python. I just started my first step towards game coding, and now iam able to animate things around the screen and makes things bounce like balls etc..
http://programarcadegames.com/
This is the tutorial which helped me a lot to do these things.This tutorial uses very legible language that is easy to understand for beginners.  Only thing i doubt about this tutorial is whether the coding is in round about way. Because when i went through some of the codes written by my friends they don't seem this lengthy.  Probably it is better for beginners to learn from the basics than to jump to the advanced stuff with few lines of code and getting all confused.
Well here is the link to my github repo for what i have dome so far using this tutorial. I've just read two chapters so far, so don't misinterpret the standard of the tutorial with my code. :)

http://programarcadegames.com/

Tuesday, 5 November 2013

Indian start-ups provides a Billion dollar oppurtunity

Indian start-ups' billion dollar opportunity

Today Indian startups provide billions of opportunities for the upcoming software "techies". A new breed of Indian software companies is now profiting from the hunger for small scale cutting-edge works.
Among the up and coming lot are business phone services provider Exotel, helpdesk software manufacturer Freshdesk, medical practice management-focused Practo , customer engagement solutions provider Capillary, and digital commerce solution provider MartJack, all of which cater to the needs of small businesses, both in India and abroad. Rather than established companies that prefer to go on a safe basis, startups that are experimenting on ideas are coming more on to the limelight. More job opportunities and core applications add to the beauty of Indian Startups.

Monday, 4 November 2013

First Aid for your pc(TIMES OF INDIA)

ClamWin, CCleaner, Recuva, Revo Uninstaller and AutoRuns for Windows

 are some of the softwares suggested for making your own first aid kit.The kit is nothing but a simple thumb drive which you can take it with you all the time, and help anyone with their PC problems.

CLAM WIN
It is a portable version of Clam Win antivirus.Sometimes the virus affected in your system may disable the antivirus software installed in your system, with clam win it is easy to detect and remove such malwares.

CCLEANER
If your Pc has turned too slow and takes minutes to open a folder, then it is because of the temporary files created by your softwares that are not anymore necessary, These occupy a huge ram space and makes the system perform sluggish.
Launch CCLEANER in your system and purge your system of this junk

RECUVA
Recuva comes with a simple  magical interface that brings you back all the permanently deleted files in your system.Some files like image files can be viewed but I  think only a list of the deleted files could be retrieved.
Hope there are better softwares on market these days.

REVO UNINSTALLER
Uninstalled software sometimes leave residue in the form of files and Registry entries. These are not easy to find and they often end up filling the precious space. 
Revo Uninstaller saves you the trouble of manually clearing these files by thoroughly uninstalling a program. 


AUTORUNS FOR WINDOWS 
If your system takes too much time to boot, then it is because of the unwanted programs that are configured to launch at the boot time. AutoRuns cut down these programs so that your system boots up faster than ever before. 


These are not all that a PC needs for a better performance. but these can be considered as a first aid before the thorough checkup.

Monday, 21 October 2013

SCOPE

There are mainly two types of scopes for python variables:

  • Local scope
  • Global scope
Global variables are accessible from all functions whereas local variables are accessible only from the function where it is declared.
Consider the following example.
----------------------------------------------------------------------------------------------------------------------------------
x = 1

def fun():
    x = 2
    print x

fun()
print x

Here the output is
2
1
-----------------------------------------------------------------
First the function fun() is invoked, when the print x statement is encountered, it looks for local variables named x if found it prints the value of local x if not it goes for global x.Since in this problem local x is available the value of global x is overwritten by local x within the function.
-----------------------------------------------------------------

x = 1

def fun():
    p = 2
    print p

fun()
print x
print p #this gives an error

Here the output is
2
1
Traceback (most recent call last):
  File "nested_scope.py", line 7, in 
    print local_var  # this gives an error
NameError: name 'local_var' is not defined
-----------------------------------------------------------------
If at all you invoke global variable within a function, if you declare another variable with the same name, then the global value will be over written(only within the function).
For eg:
-----------------------------------------------------------------
x = 1

def fun():
    global x
    x = 10
    print x

fun()

print x
 
The output will be:
10
10
-----------------------------------------------------------------

./ method to execute a python file

A file can be executed from the terminal using
./filename.py
by typing a special command in the beginning of the filename.
The very first byte of the file must start with a # symbol followed by a !,followed by the path.
For eg,
#!/usr/bin/python

Tuesday, 1 October 2013

REGULAR EXPRESSIONS

Regular expressions are used for pattern matching.The Python "re" module provides regular expression support.

import re

s1 = 'this is a nice line!'

pat1 = 'nice'

print re.search(pat1, s1)

If pattern matching is successful a match object is returned else the function returns None.
pat1 = r'^is'

print re.search(pat1, s1)

'r' before the string gives a special meaning to it. By using that we say the string is raw or the special characters used withing the string doesn't have special meaning.
 
Ordinary characters just match themselves exactly.
The characters which do not match themselves because they have special meanings are:
 . ^ $ * + ? { [ ] \ | ( ) 
  • . (a period) -- matches any single character except newline '\n'
  • \w -- (lowercase w) matches a "word" character: a letter or digit or underscore. Note that although "word" is the mnemonic for this, it only matches a single word char, not a whole word. \W (upper case W) matches any non-word character.
  • \b -- boundary between word and non-word
  • \s -- (lowercase s) matches a single whitespace character -- space, newline, return, tab, form. \S (upper case S) matches any non-whitespace character.
  • \t, \n, \r -- tab, newline, return
  • \d -- decimal digit [0-9]
  • ^ = start, $ = end -- match the start or end of the string
  • \ -- inhibit the "specialness" of a character. So, for example, use \. to match a period or \\ to match a slash. If you are unsure if a character has special meaning, such as '@', you can put a slash in front of it, \@, to make sure it is treated just as a character.

Friday, 20 September 2013

Lambda forms

By popular demand, a few features commonly found in functional programming languages like Lisp have been added to Python.
With the lambda keyword, small "anonymous" functions can be created.
Here’s an example:
>>> a=map(lambda x:x*x,range(10))
>>> a
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]


Lambda forms can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda forms can reference variables from the containing scope:
While using lambda there is no scope for using loops and all.
Only a single statement can be included.

Filter(), Map() and Reduce()-----> Tools for functional programming

Filter() map() and reduce() are built in functions. These are very useful while used with lists. Here are the details.

Filter()


Syntax:
                filter(function,sequence)


returns a sequence consisting of those elements from the sequence for which function(element) is true. If sequence is a string or tuple, the result will be of the same type, otherwise, it is always a list.
 For example, to compute a sequence of numbers not divisible by 2 and 3:
 >>> def f(x):
...     return ((x%2!=0) and (x%3!=0))
...
>>> filter(f,range(0,10))
[1, 5, 7]

Map()

Syntax:
               map(function,sequence)
Calls the function() for each value in the sequence and stores the return value in a list. For example:
>>> def cube(x):
...     return x*x*x
...
>>> map(cube,range(10))
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
>>> 
More than one sequence may be passed; the function must then have as many arguments as there are sequences and is called with the corresponding item from each sequence (or None if some sequence is shorter than another). For example:
>>> def f(x,y):
...     return x+y
...
>>> seq=range(8)
>>> map(f,seq,seq)
[0, 2, 4, 6, 8, 10, 12, 14]
>>>

 

Reduce()

Syntax:
                  reduce(function,sequence)              

returns a single value constructed by calling the binary function "function" on the first two items of the sequence, then on the result and the next item, and so on. For example, to compute the sum of the numbers 1 through 10:
>>>
>>> def f(x,y):
...     return x+y
... 
>>>reduce(f,range(1,11));
55

If there’s only one item in the sequence, its value is returned; if the sequence is empty, an exception is raised.A third argument can be passed to indicate the starting value.

My first game code...

/*                              Chaythanya
   If you are using turbo cpp compiler try to include conio.h ang uncomment the
   function clrscr() for better looks */
#include<stdio.h>
#include<stdlib.h>
//#include<conio.h>
char a[5][5];
char pa[5][5];
int pc=0;
int r,c;
void intro(char* player);
int find(int choice);
void firstdisplay();
void make();
void play();
void display(char a[5][5]);
void play();
void intro(char* player)
{
    printf("\n\t Welcome %s.. here are the rules of the game\n",player);
    firstdisplay();
    printf("\n\t This is the board, there are no empty columns each column is filled with either mine or character ");
    printf("\n\t choose the appropriate no: to open the block\n\t Game begins!!...\n\n\n"); 
}
void make()
{
    int i,j;
    int d=65;
    for(i=0;i<5;i++)
    {
        for(j=0;j<5;j++)
        {
            pa[i][j]=' ';
            if(pc==1)
            {
            if(5*(i+j)%3==0)
                a[i][j]='X';
            else
            {
                if((d!=120)&&(d!=88))
                {
                    a[i][j]=d;
                    d++;
                }
            }
            }
            else
            {
            if((i+j)%(pc+1)==0)
                                a[i][j]='X';
                        else
                        {
                                if((d!=120)&&(d!=88))
                                {
                                        a[i][j]=d;
                                        d++;
                                }
                        }
            }

        }
    }
    firstdisplay();
}
void firstdisplay()
{
    printf("\t _____ _____ _____ _____ _____ \n");
        printf("\t|     |     |     |     |     | \n");
        printf("\t| 1   |  2  |  3  | 4   |  5  |\n");
        printf("\t|_____|_____|_____|_____|_____|\n");
        printf("\t|     |     |     |     |     |\n");
        printf("\t| 6   |  7  |  8  |  9  | 10  |\n");
        printf("\t|_____|_____|_____|_____|_____|\n");
        printf("\t|     |     |     |     |     |\n");
        printf("\t| 11  | 12  | 13  | 14  | 15  |\n");
        printf("\t|_____|_____|_____|_____|_____|\n");
    printf("\t|     |     |     |     |     |\n");
        printf("\t| 16  | 17  | 18  | 19  | 20  |\n");
        printf("\t|_____|_____|_____|_____|_____|\n");
    printf("\t|     |     |     |     |     |\n");
        printf("\t| 21  | 22  | 23  | 24  | 25  |\n");
        printf("\t|_____|_____|_____|_____|_____|\n");
}
void play()
{
    int b;
    printf("\n\t Enter the block you want to open:");
    scanf("%d",&b);
    int success= find(b);
    if(!success)
    {
       
        pa[r][c]=a[r][c];
        if(a[r][c]=='X')
        {
            display(a);
            return;
        }
        else
        {        display(pa);
                play();
        }
    }
    else
    {
        printf("\n\n\t Wrong choice!!.. try again!!\n\n");
        display(pa);
        play();
    }
}

int find(int choice)
{
    if(choice==1){
                r=0;
                c=0;
        return 0;
        }
        else if(choice==2){
                r=0;
                c=1;
        return 0;

        }
        else if(choice==3){
                r=0;
                c=2;
        return 0;

        }
        else if(choice==4){
                r=0;
                c=3;
        return 0;

        }
        else if(choice==5){
                r=0;
                c=4;
        return 0;

        }
        else if(choice==6){
                r=1;
                c=0;
        return 0;

        }
        else if(choice==7){
                r=1;
                c=1;
        return 0;

        }
        else if(choice==8){
                r=1;
                c=2;
        return 0;

        }
        else if(choice==9){
                r=1;
                c=3;
        return 0;

        }
    else if(choice==10){
                r=1;
                c=4;
        return 0;

        }
        else if(choice==11){
                r=2;
                c=0;
        return 0;

        }
        else if(choice==12){
                r=2;
                c=1;
        return 0;

        }
        else if(choice==13){
                r=2;
                c=2;
        return 0;

        }
        else if(choice==14){
                r=2;
                c=3;
        return 0;

        }
        else if(choice==15){
                r=2;
                c=4;
        return 0;

        }
        else if(choice==16){
                r=3;
                c=0;
        return 0;

        }
        else if(choice==17){
                r=3;
                c=1;
        return 0;

        }
        else if(choice==18){
                r=3;
                c=2;
        return 0;

        }
        else if(choice==19){
                r=3;
                c=3;
        return 0;

        }
        else if(choice==20){
                r=3;
                c=4;
        return 0;

        }
        else if(choice==21){
                r=4;
                c=0;
        return 0;

        }
        else if(choice==22){
                r=4;
                c=1;
        return 0;

        }
        else if(choice==23){
                r=4;
                c=2;
        return 0;

        }
        else if(choice==24){
                r=4;
                c=3;
        return 0;

        }
        else if(choice==25){
                r=4;
                c=4;
        return 0;

        }
        else
        return 1;
}
  

void display(char a[5][5])
{
   

    printf("\t _____ _____ _____ _____ _____ \n");
        printf("\t|     |     |     |     |     | \n");
        printf("\t|  %c  |  %c  |  %c  |  %c  |  %c  |\n",a[0][0],a[0][1],a[0][2],a[0][3],a[0][4]);
        printf("\t|_____|_____|_____|_____|_____|\n");
        printf("\t|     |     |     |     |     |\n");
        printf("\t|  %c  |  %c  |  %c  |  %c  |  %c  |\n",a[1][0],a[1][1],a[1][2],a[1][3],a[1][4]);
        printf("\t|_____|_____|_____|_____|_____|\n");
        printf("\t|     |     |     |     |     |\n");
        printf("\t|  %c  |  %c  |  %c  |  %c  |  %c  |\n",a[2][0],a[2][1],a[2][2],a[2][3],a[2][4]);
        printf("\t|_____|_____|_____|_____|_____|\n");
        printf("\t|     |     |     |     |     |\n");
        printf("\t|  %c  |  %c  |  %c  |  %c  |  %c  |\n",a[3][0],a[3][1],a[3][2],a[3][3],a[3][4]);
        printf("\t|_____|_____|_____|_____|_____|\n");
        printf("\t|     |     |     |     |     |\n");
        printf("\t|  %c  |  %c  |  %c  |  %c  |  %c  |\n",a[4][0],a[4][1],a[4][2],a[4][3],a[4][4]);
        printf("\t|_____|_____|_____|_____|_____|\n");

}
void main()
{
    char player,choice;
    do
    {
    pc++;
//    clrscr();   
    printf("\t\t MINE SWEEPER------> DEMO");
    printf("\n\t\t*************************");
    printf("\n\n\tEnter the name of the player:");
    scanf(" %s",&player);
    intro(&player);
    make();
    play();
    printf ("\n\n\t GAME OVER!!\n\n");
        printf("\n\n\tDo you wish to continue?(Y/n)");
        scanf(" %c",&choice);
    if(pc>3)
        {
                printf("\n\n\tOOops!! You have exceeded your maximum no: of chances well.. Better luck next time..\n\n");
                exit(1);
        }

    }
        while((choice=='Y'||choice=='y'));

                             
}






































Wednesday, 18 September 2013

Modules and Modular programming

If you want to develop programs which are easily readable, reliable and for which easy debugging is possible without too much effort, you have to use some kind of modular software design...
Especially if your application has a certain size. Modular programming is a  technique to split the code into separate parts. These parts are called modules.

But how do we create modules in Python?
A module in Python is just a file containing Python definitions and statements. The module name is the file name by removing the suffix ".py". For example, if the file name is fibb.py, the module name is fibb.
This is how we create modules.We save the following code in the file fibb.py:
def fib(n):
     if n == 0:
       return 0
     elif n == 1: 
       return 1 
     else:
       return fib(n-1) + fib(n-2) 
def fib1(n): 
     a, b = 0, 1 
     for i in range(n):
       a, b = b, a + b 
return a

Now save this file and open the interactive python promt. type in the following code
>>> import fibb
>>> fibb.fib(3)
2
>>> fibb.ifib(3)
2
in this way you can use modules instead of typing the code each time..

There are many inbuilt python modules also. One such example is "math"
>>> import math
>>>math.sin(0)
0.0
>>> dir(math)
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']


These are the other operations defined on the module math.
There are different kind of modules:
  • Those written in Python
    They have the suffix: .py
  • Dynamically linked C modules
    Suffixes are: .dll, .pyd, .so, .sl, ...
  • C-Modules linked with the Interpreter:
    It's possible to get a complete list of these modules:

 

Memory----> Python rocks!

Advantage of automatic memory management--> Demo

 In c language we have to explicitly deallocate the memory after use. Folowing is a set of C code which runs an infinite loop.
#define LEN 10000
void fun()
{
    char *p;
    p = malloc(LEN);
    if(p == 0) {
        perror("malloc failed");
        exit(1);
    }
    free(p);
}
main()
{
    /* call "fun" in an infinite loop */
    while(1) {
        fun();
    }
}

In this case the CPU is fully engaged but the memory consumption remains almost constant because as soon as the memory is allocated it is deallocated using free().

After the program is terminated....





This is another example where memory is not deallocated... Careful the system might get stuck...
#include <stdlib.h>
#define LEN 10000
void fun()
{
    char *p;
    p = malloc(LEN);
    if(p == 0) {
        perror("malloc failed");
        exit(1);
    }
}
main()
{
    while(1) {
        fun();
        usleep(10);
 /* slow down the loop a little bit */
    }
 }
Here the memory runs out..
Where as running this python code we get the same result as in the first program..

while True:
    a = [1] * 1000000
First a list is created and a referenced to it. when a is again referenced to another list then the first list is unreferenced and is not accessible hence it is automatically deleted or removed from the memory





List/Set/dictionary Comprehensions

Comprehension is an elegant way to define and create lists/Dictionaries/sets in Python.

 List comprehension

>>> a=[1,2,3,4]
>>> b=[x+1 for x in a]
>>> print b
[2, 3, 4, 5]
 
This can be used as a substitute for map function.
It can even have conditional statements for eg:
 >>> a=range(50)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
>>> b=[x for x in a if ((x%8)==0 and (x%3)==0)]
>>> b
[0, 24, 48]

This piece of code prints all the nos between 0 and 50 thos are divisible by both 8 and 3. 
This is how comprehensions make python more attractive!

Set comrehension

 Set comprehension also works like list comprehension with an exception that it does not have any duplicate elements. Further there is a slight difference in the syntax also.
This is how we can use set comprehensions:
 >>>S= {-4, -2, 1, 2, 5, 0}
 Write a triple comprehension those value is a list of all three element tuples (i,j,k) such that i,j,k are elements of S whose sum is zero.
>>>S = {-4, -2, 1, 2, 5, 0}
>>>zero_sum_list ={(x,y,z) for x in S for y in S for z in S if (x+y+z)==0}
This is an example for triple comprehension.


Modifying the above comprehension so that the resulting list does not include (0,0,0) we get:
>>>excluded_zero_sum_list ={(x,y,z) for x in s for y in s for z in s if ((x+y+z)==0} and (x or y or z)!=0)] 

Dictionary comprehension


Dictionary comprehensions are used to create dictionaries. Almost like the above two types. These are mainly used when we have a relation between the 'key' and the 'value' and the same relation is repeated throughout the dictionary.
Here is a n example:
Using `range', write a dictionary comprehension: the keys of the dictionary are values from 0 to 4 and the value corresponding to each key is the square of the key.

>>>square_dict ={x:x*x for x in range(5)]
>>> square_dict
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}


Shallow and deep copying

According to reference semantics, we know that only reference are meaningful than real objects.
There are certain crucial problems, which can occur when copying mutable objects, like copying lists and dictionaries.

Copying with the slice operator

It's possible to completely copy shallow lists with the slice operator without any problem, which is described below:
>>> l=[1,2,3,4]
>>> l2=l[:]
>>> print l
[1, 2, 3, 4]
>>> print l2
[1, 2, 3, 4]
>>> l.append(5)
>>> print l2
[1, 2, 3, 4]
>>> print l
[1, 2, 3, 4, 5]

But as soon as a list contains sublists, we have the some difficulty, i.e. just references to the sublists are copied and not the actual members of the lists.

>>> #shallow copying
...
>>>
>>>
>>> a=[1,2,3,[4,5],6,7,[8,9],10]
>>> b=a
>>> c=a[:]
>>> print b
[1, 2, 3, [4, 5], 6, 7, [8, 9], 10]
>>> print c
[1, 2, 3, [4, 5], 6, 7, [8, 9], 10]
>>> a.append(11)
>>> print a
[1, 2, 3, [4, 5], 6, 7, [8, 9], 10, 11]
>>> print b
[1, 2, 3, [4, 5], 6, 7, [8, 9], 10, 11]
>>> print c
[1, 2, 3, [4, 5], 6, 7, [8, 9], 10]
>>> a[3].append('innerlist')
>>> print a
[1, 2, 3, [4, 5, 'innerlist'], 6, 7, [8, 9], 10, 11]
>>> print b
[1, 2, 3, [4, 5, 'innerlist'], 6, 7, [8, 9], 10, 11]
>>> print c
[1, 2, 3, [4, 5, 'innerlist'], 6, 7, [8, 9], 10]
>>>
 
This behaviour is depicted in the following diagram: 

In this case, while lst1 is copied into lst2 only the reference which was there in lst1 is copied and not the original values.
If you assign a new value to the 0th Element of one of the two lists, there will be no side effect. Problems arise, if you change one of the elements of the sublist. 
           
                   
              Copying a list with sublists



The following diagram depicts what happens, if one of the elements of a sublist will be changed: Both the content of lst1 and lst2 are changed.

         
                 Copying lists containing sublists

Method of deep copying

Deepcopy is a "method" which needs to be imported from the module copy.

The following script uses our example above and this method:
>>> from copy import deepcopy
>>>lst1 = ['a','b',['ab','ba']] 
>>>lst2 = deepcopy(lst1) 
>>>lst2[2][1] = "d" 
>>>lst2[0] = "c"; 
>>>print lst2
['c','b',['ab','d']]
>>> print lst1
['a','b',['ab','ba']]

                    Copy a list with Deep-Copy











Friday, 13 September 2013

PYTHON-------> OVERVIEW OF THE KEY CONCEPTS

Reference semantics

Everything in Python is an object and Python passes references to those objects i.e. consider the following case
 >>> a=[1,2,3,"hello",4,"hai"]
>>> b=a

while this code is interpreted this is what internally happens.

 a--------------->[1,2,3,"hello",4,"hai"]
                                ^
                                |
                                |
                                b
Internally in the memory there is only one list "[1,2,3,"hello",4,"hai"]" and both "a" and "b" are mere names with which you can acees the memory location.
this can be demonstrated by the following set of code.
>>> a=[1,2,3,"hello",4,"hai"]
>>> b=a
>>> a.append("change")
>>> print b
[1, 2, 3, 'hello', 4, 'hai', 'change']

The change made to "a" internally reflects to "b" this makes it clear that "a" and "b" refers to the same thing.
If we pass an immutable object to a method, it references the original object, and you can't change the object.

Memory management

 In C language we use malloc() to allocate memory and free() to free the allocated memory.IF we forget to free() the memory that has been allocated serious problems may occur and there are chances for your program to get "crashed".
Python introduces a solution for this by "automatic memory management". Python uses reference counting to detect inaccessible objects. The "garbage collection" module provides functions to force garbage collection.It uses something called "ref-count" to do this. 

Reference counting and garbage collection

Python automatically deletes inaccessible memory locations. For example consider the following set of code.
 >>> a=[1,2,3,"hello",4,"hai"[ref_count=1]] #ref_coutn is a hypothetical concept and not a member of the list]
>>> b=a
>>> a.append("change")
>>> print b
[1, 2, 3, 'hello', 4, 'hai', 'change'[ref_count=2]]
>>> c=b
>>> c=(1,2,3)
>>> b="steve"
>>> a="john"
here this is what happens
step1
-----------------------------------------------------------------------
a--------------->[1,2,3,"hello",4,"hai"]
                                ^ 

                                |

                                |

                                b
a--------------->[1,2,3,"hello",4,"hai","change"[ref_count=2]]   
                                ^ 

                                |

                                |

                                b
 step2
----------------------------------------------------------------------------------
a--------------->[1,2,3,"hello",4,"hai","change"[ref_count=3]]
                                ^  ^

                                |   |

                                |   |

                                b  c
step3
---------------------------------------------------------------------------------
a--------------->[1,2,3,"hello",4,"hai","change"[ref_count=2]]
                                ^ 

                                |

                                |

                                b                c----->(1,2,3)
step4
-----------------------------------------------------------------------------------

a--------------->[1,2,3,"hello",4,"hai","change"[ref_count=1]]
                              
b------>"steve"
c------->(1,2,3)

step5
------------------------------------------------------------------------------------

""----------------------->>>[1,2,3,"hello",4,"hai","change"[ref_count=0]] 
 a------>"john"
 b------>"steve"
c-------->(1,2,3)

************************************************************
Now it is evident that there is no name with which we can access th list
[1,2,3,"hello",4,"hai","change"[ref_count=0]]
and the ref_count is 0 hence python gets to know that it is a mere waste of memory therefore python automatically releases that memory space.