Monday 25 July 2011

Pygame - Source code of my game

This is one of my simple game developed by using pygame module. In this game I demonstrate a simple logic. I think this source code will give you the basic idea about the programming. If you are interested in game programming also you are a beginner in this field , then i am sure this code must be useful to you.

# Import a library of functions called 'pygame'
import pygame
import random

# Initialize the game engine
pygame.init()
black = [ 0, 0, 0]

#Colors used in this game
white = [255,255,255]
green=[0,255,0]

#set the music
music=pygame.mixer.Sound("song.wav") 
music.play()

#Specify the comments display on the screen after the game
basicfont=pygame.font.Font('freesansbold.ttf',32)
gameover=basicfont.render("GAME OVER",1,green)
gameoverrect=gameover.get_rect()

#Display the result on the screen
scoreboard=pygame.font.Font(None,32)

# Set the height and width of the screen
screen = pygame.display.set_mode([600, 500])
pygame.display.set_caption("Point collection")

#coordinates
x_coord=0
y_coord=250
clock = pygame.time.Clock()

#create lists
atkr=[]
point=[]
atkb=[]

# Loop 10 times and add a images in a random x,y position
for i in range(10):
    x=random.randrange(200,600)
    y=random.randrange(0,500)
    atkr.append([x,y])

for i in range(5):
    x=random.randrange(0,600)
    y=random.randrange(0,500)
    point.append([x,y])

for i in range(10):
    x=random.randrange(0,600)
    y=random.randrange(0,500)
    atkb.append([x,y])

#Loop until the user clicks the close button.
done=False
move_x=0
move_y=0
score=0

while done==False:
    music.play()
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done=True # Flag that we are done so we exit this loop

        # Ketboard used to control the player in left,right,top and bottom
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                move_x=-3            
            if event.key == pygame.K_RIGHT:
                move_x= 3
            if event.key==pygame.K_UP:
                move_y=-3

        if event.key==pygame.K_DOWN:   
        move_y=3      
         
        if event.type==pygame.KEYUP:
            if event.key==pygame.K_LEFT:
                move_x=0

        if event.key==pygame.K_RIGHT:
                move_x=0
            if event.key==pygame.K_UP:
                move_y=0
            if event.key==pygame.K_DOWN:
        move_y=0   
                           
#Move the object according to the speed vector.
    x_coord=x_coord+move_x
    y_coord=y_coord+move_y
    screen.fill(black)

# Create player
    player=pygame.image.load("man.jpg").convert()
    screen.blit(player,[x_coord,y_coord])
    rect1=pygame.Rect(x_coord,y_coord,25,35)
    player.set_colorkey(black)

# Process each atkr in the list
    for i in range(len(atkr)):
        atkr_img=pygame.image.load("im.gif").convert()
        screen.blit(atkr_img,atkr[i])
        # Move the atkr left three pixel
        atkr[i][0]-=3
        if rect1.collidepoint(atkr[i][0],atkr[i][1]):
        score=score-1
            y=random.randrange(0,500)
            atkr[i][1]=y
            x=random.randrange(590,600)
            atkr[i][0]=x     
        # If the atkr has moved off the left of the screen
        if atkr[i][0] <0:
            # Reset it just right of the screen
            y=random.randrange(0,500)
            atkr[i][1]=y
            x=random.randrange(590,600)
            atkr[i][0]=x    
      
    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # Process each point list elements
    for i in range(len(point)):
        point_img=pygame.image.load("b2-17.png").convert()
        screen.blit(point_img,point[i])

        # Move the point image down three pixel
        point[i][1]+=3
          if rect1.collidepoint(point[i][0],point[i][1]):
            score=score+1
            y=random.randrange(-500,-10)
            point[i][1]=y
            x=random.randrange(0,600)
            point[i][0]=x

        # If the image has moved off the bottom of the screen
        if point[i][1] > 500:
            # Reset it just above the top
            y=random.randrange(-500,-10)
            point[i][1]=y
            # Give it a new x position
            x=random.randrange(0,600)
            point[i][0]=x

    for i in range(len(atkb)):
        atkb_img=pygame.image.load("alien.png").convert()
        screen.blit(atkb_img,atkb[i])
        atkb_img.set_colorkey(white)
        # Move the image top three pixel
        atkb[i][1]-=3       
        if rect1.collidepoint(atkb[i][0],atkb[i][1]):
            score=score-1
            y=random.randrange(490,500)
            atkb[i][1]=y
            x=random.randrange(0,600)
            atkb[i][0]=x

        # If the imaged has moved off the top of the screen
        if atkb[i][1] <0:
            # Reset it to the new position
            y=random.randrange(490,500)
            atkb[i][1]=y
            x=random.randrange(0,600)
            atkb[i][0]=x
    screen.blit(scoreboard.render("score"+str(score),4,white),[40,40])

    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()   
    clock.tick(20)
    if score<-2:
        screen.blit(gameover,gameoverrect)
        pygame.display.flip()
        done=True  
pygame.quit ()

You can download the code from here. If you have any suggestion regarding my game, please inform me.
 Click  Pygame  to show more details about pygame and game development.

Some Basic Linux Commands


In this post I want to discuss about some basic Linux Commands. I think this post will useful for all beginners who are interested in Linux. 
Linux terminal is one of the very good command line interfaces out there. Knowing Linux commands  may help you better understand your system and increase your efficiency. Opening your terminal in Ubuntu is very easy. Just go to..
 
Applications->Accessories->Terminal.

The prompt of the terminal shows something like this:

anoop@anoop-laptop:~$

The first name is your username and the one after the @ is your hostname.
After the colon ~ represents your home folder(you always start at your home folder by default)
$ is the prompt symbol in linux just like > in windows ( C:\> )

A Linux command normally consists of three parts: the command itself, the command options, and its arguments. For instance, the following example shows what a linux command looks like.

useradd -m -G sales India

This example consists of three parts, useradd, which is the command; -m and -G sales, which are both options; and India, which is a generic argument.

There are many Linux commands are there, Here I want to discuss only about some basic commands that we are frequently used.

cd command: Just like in Windows changes the diretory(case sensitive). But 
                     cd.. or cd. doesn't work here.
                     Usage: username@computer:~$ cd Documents
                     You can use a directory in place of Documents.

ls command: This command lists the files in your current folder. use ls -al to
                    display all files(includes hidden) and their details.
                    Usage : username@computer:~$ ls -al

mkdir command: Allows you to create directories.
                          Usage: username@computer:~$ mkdir myvideo

man command: opens a help file for a command. Press Q to exit.
                        Usage: username@computer:~$ man ls

cat command: To view the contents of a file in current directory.
                      Usage: username@computer:~$ cat text1.txt

rm command: Deletes/Removes a file from the directory().
                      Usage: username@computer:~$ rm text1.txt 

cp command: Makes a copy of the file. The original file remains there.
                     Usage: username@computer:~$ cp text1.txt copyoftext1.txt
pwd command: This command prints the current working directory.
                        Usage: username@computer:~$ pwd

mv command: Moves the file form one directory to another.The original file is 
                      moved.
                      Usage: username@computer:~$ mv /home/Desktop/text1.txt /home
cal command: Displaying a calender.
                      Usage: username@computer:~$ cal

clear command: Clear your screen so that you can see in a better way what you are doing.
                      Usage: username@computer:~$ clear

uname command : Displaying system information with uname and  hostname. 
Uname command with no arguments will  just   show   the kind of  kernal  you are using.
                        uname -r display the kernal version.
                        uname -p display the type of CPU.
                        uname -a display all the details of your Computer.
                        Usage: username@computer:~$ uname -a

wc command: wc means word count. Used to know how many words there are in a file.
                         Usage: username@computer:~$ wc filename
date command: Display the current date and time.
                         Usage: username@computer:~$ date

These are some basic commands we are frequently used in Linux command prompt. I will show you some other commands in the next post.

Sunday 24 July 2011

What is AJAX?

    In this post I introduce to you some basic concept of AJAX. As the part of my project I need to create one dynamic website, at that time I heard about this powerful dynamic web development tool. I want to share my learning experience with this post, I think it will useful for all beginners who are interested in Ajax.

    In the 1990s, most web sites were based on complete HTML pages;  That is static web pages. each user action required that the page be re-loaded from the server (or a new page loaded). Each time a page is reloaded due to a partial change, all of the content must be re-sent instead of only the changed information. This can place additional load on the server and use excessive bandwidth. At last we have found a solution for this problem. The term Ajax was introduced by Jesse James Garrett  on February 18, 2005.

What is Ajax?
AJAX is a technique for creating fast and dynamic web pages.

AJAX = Asynchronous JavaScript and XML.

AJAX is not a new programming language, but a new way to use existing standards.

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.

Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

Now I think you got an idea about what is Ajax. Next we discuss about the working of Ajax. 

How Ajax works?
This figure shows the working steps of Ajax on the Internet. Ajax uses a programming model with display and events. These events are user actions, they call functions associated to elements of the web page.
Interactivity is achieved with forms and buttons. DOM allows to link elements of the page with actions and also to extract data from XML files provided by the server.
To get data on the server, XMLHttpRequest provides two methods:
  • open: create a connection.
  • send: send a request to the server.
Data furnished by the server will be found in the attributes of the XMLHttpRequest object:
  • responseXml for an XML file or
  • responseText for a plain text.
Take note that a new XMLHttpRequest object has to be created for each new file to load.
Note : AJAX applications are browser- and platform-independent!

AJAX is based on Internet standards. The following technologies are incorporated with Ajax:
  • HTML or XHTML and CSS for presentation
  • the Document Object Model (DOM) for dynamic display of and interaction with data
  • XML for the interchange of data, and XSLT for its manipulation
  • the XMLHttpRequest object for asynchronous communication
  • JavaScript to bring these technologies together



Monday 18 July 2011

Lisp - Installation and Features

In this post I want to discuss about how to install and start coding with Lisp. Before start coding we must need to install the lisp in your system, for that open your terminal in your system and type

sudo apt-get install clisp

with in few minutes clisp (Common Lisp) is installed in your system. you must check to verify that lisp is  correctly installed or not in your system, for that just type clisp in terminal, if it is correctly installed then it will display on the window like this

Now lisp was successfully installed in your system. Now you can start coding. Like python, we can run the lisp code in two ways. Interpreted mode and batch mode. in interpreted mode, programmer write the code line by line in the terminal, clisp interpreter process and return result. In batch mode, programmer can write code as a file, after that execute it.
Now I show you an example in two different method. 

Example : Program to print "Hello world"
In Interpreted method just type the (print "Hello world") in terminal.

[1]> (print "Hello world")

"Hello world"
"Hello world"
[2]>

In batch method open any editor and type (print "Hello world ") after that save the file with .lsp extension. Run the program by just type clisp pgmname.lsp
anoop@anoop-laptop:~$ clisp hello.lsp
"hello world"

I will discuss more complex examples in the next post's. Now i want to discuss some important features of lisp.


Significant Language Features

  • Atoms & Lists - Lisp uses two different types of data structures, atoms and lists.
    • Atoms are similar to identifiers, but can also be numeric constants
    • Lists can be lists of atoms, lists, or any combination of the two
  • Functional Programming Style - all computation is performed by applying functions to arguments. Variable declarations are rarely used.
  • Uniform Representation of Data and Code - example: the list (A B C D)
    • a list of four elements (interpreted as data)
    • is the application of the function named A to the three parameters B, C, and D (interpreted as code)
  • Reliance on Recursion - a strong reliance on recursion has allowed Lisp to be successful in many areas, including Artificial Intelligence.
  • Garbage Collection - Lisp has built-in garbage collection, so programmers do not need to explicitly free dynamically allocated memory. 

 

Areas of Application 

Below is a short list of the areas where Lisp has been used:

  • Artificial Intelligence
    1. AI Robots
    2. Computer Games (Craps, Connect-4, BlackJack)
    3. Pattern Recognition
  • Air Defense Systems
  • Implementation of Real-Time, embedded Knowledge-Based Systems
  • List Handling and Processing
  • Tree Traversal (Breath/Depth First Search)
  • Educational Purposes (Functional Style Programming)

Lisp - History

Today I started the project 'Design of a Lisp Interpreter with a web front end'. I doing this project as the part of my post graduation.  In this post I want to discuss about the history and basics of Lisp.

what is Lisp?  Lisp is a family of computer programming languages with a long history. Lisp was invented by John McCarthy in 1958 while he was at the Massachusetts Institute of Technology (MIT) . The following figure shows the Lisp machine in the MIT museum.

McCarthy published its design in a paper on 1960.
Lisp was first implemented by Steve Russell on an IBM 704 computer. Russell had read McCarthy's paper, and realized  that the Lisp eval function could be implemented in machine code. The result was a working Lisp interpreter which could be used to run Lisp programs, or more properly, 'evaluate Lisp expressions.'

 Lisp is the second oldest high-level programming language in widespread use today; Fortran is the first oldest high-level programming language. Today, the most widely known general-purpose Lisp dialects are Common Lisp, Scheme, and Clojure. Other dialects are Emacs Lisp, AutoLISP, Newlisp, Arc, SKILL,Racket, Logo, Clojure, ISLISP.





































The first complete Lisp compiler, written in Lisp, was implemented in 1962 by Tim Hart and Mike Levin at MIT.

I am sure, now you must think that 'lisp is an oldest programming language, then today what is the relevance of this language?' I have a good answer for this question. I agree that lisp is an oldest programming language, also it is still widely used in Artificial intelligence. Hence it is not an useless language.

 As one of the earliest programming languages, Lisp pioneered many ideas in computer science, including tree data structures, automatic storage management, dynamic typing, and the self-hosting compiler.
The name LISP derives from "LISt Processing". Linked lists are one of Lisp language's major data structures, and Lisp source code is itself made up of lists.

Lisp was closely connected with the artificial intelligence research community, especially on PDP-10 systems. Lisp was used as the implementation of the programming language Micro Planner which was used in the famous AI system SHRDLU.

Lisp is an expression-oriented language. Unlike most other languages, no distinction is made between "expressions" and "statements"; all code and data are written as expressions. When an expression is evaluated, it produces a value  which then can be embedded into other expressions. Each value can be any data type.

McCarthy's 1958 paper introduced two types of syntax: S-expressions (Symbolic expressions, also called "sexps"), which mirror the internal representation of code and data; and M-expressions (Meta Expressions), which express functions of S-expressions. M-expressions never found favor, and almost all Lisps today use S-expressions to manipulate both code and data.

In Lisp all program code is written as s-expressions (symbolic expressions), or parenthesized lists. A function call or syntactic form is written as a list with the function or operator's name first, and the arguments following; for instance, a function f that takes three arguments might be called using (f arg1 arg2 arg3).

These are the basic concepts of Lisp. I will explain more about Lisp in the next post.

Sunday 17 July 2011

Linked list implementation

In this post we can show how to implement a linked list in python.
In computer science , a linked list is a data structure used for collecting a sequence of objects, which allows efficient addition, removal and retrieval of elements from any position in the sequence. It is implemented as nodes, each of which contains a reference (i.e., a link) to the next and/or previous node in the sequence.

Singly-linked-list.svg

        A linked list whose nodes contain two fields: an integer value and a link to the next node

Linked lists are among the simplest and most common data structures. They can be used to implement several other common abstract data structures, including stacks, queues, associative arrays, and symbolic expressions.

The principal benefit of a linked list over a conventional array is that the list elements can easily be added or removed without reallocation or reorganization of the entire structure because the data items need not be stored contiguously in memory or on disk. Linked lists allow insertion and removal of nodes at any point in the list.
In python, we can simply implement a linked list by using class.

class node:
    def __init__(self):
        self.data = None # contains the data
        self.next = None # pointer to next node
class linked_list:
    def __init__(self):
        self.pointer = None
    def add_node(self, data):
        new_node = node() # create new node
        new_node.data = data
        new_node.next = self.pointer # Link the pointer to the  previous node
        self.pointer = new_node #  set the current node to the new one.
    def list_print(self):
        node = ll.pointer
        while node:
            print node.data
            node = node.next
ll = linked_list() # Create an object of class 'Linked_list'
ll.add_node(21)
ll.add_node(32)
ll.add_node(45)
ll.list_print() # Print the node data

 Output:
anoop@anoop-laptop:~$ python linked.py
45
32
21


Program to find the power of a number using recursion

In the following example shows how to find the power of a number using recursion. 

def power(a,b):
    if b==0:
        return 1
    elif a==0:
        return 0
    elif b==1:
        return a
    else:
        return a*power(a,b-1)

print power(2,4)

Output:  16

Here the function 'power()' recursively called to find the power of a number.
This is the simple way to find the power of a number. But it is not a good way, that is it is not optimized. It means, suppose when the given power of a number is 100, then the function 'power()' is recursively called 99 times, also time complexity increases. 

Following program shows the optimized solution for the same problem.


def power(x,y):
    if y==0:
        return 1
    elif x==0:
        return 0
    elif y==1:
        return x
    elif y%2==0:
        var_even=power(x,y/2)
        return var_even*var_even
    else:
        var_odd=power(x,(y-1)/2)    
        return x*var_odd*var_odd
    
print power(5,10)
Output: 9765625

This is the optimized solution. Here also use the recursion, at the same time optimized recursive calls are done to find the power of a number.
That is, suppose 'n' is the power of a number 'x', and also it is an even number, then x^n=( x^n/2)*(x^n/2).
If it is in the case of odd number, x^n=x*(x^(n-1)/2)*(x^(n-1)/2). In this optimized case, the number of iterations are reduced, also we can reduce the time complexity.


Friday 8 July 2011

Selection sort using python

def selection(list1):
        x=0
        while(x<len(list1)):
                small_index=x
                for y in range(x+1,len(list1)):
                        if list1[y]<list1[small_index]:
                                small_index=y
                list1[x],list1[small_index]=list1[small_index],list1[x]
                x+=1

        print "\nSorted list is : "
        print list1


def main():
        #Unsorted list
        list1=[5,2,8,6,5,9,0,3,11,54,67,34]
        selection(list1)

if __name__=='__main__':
        main()

Monday 4 July 2011

List comprehensions

    Python supports a concept called 'list comprehensions'. It can be used to construct lists in a very natural and easy way. The following are common ways to describe lists (or sets,or tuples, or vectors) in mathematics
     S = {: x in {0...9}}
     V = (1,2,4,8,...,2¹²)
    M = {x | x in S and x even }
In python we can written  it as,

>>> S=[x**2 for x in range(10)]
>>> V=[2**i for i in range(13)]
>>> M=[x for x in S if x%2==0]
Output
>>> print S; print V; print M
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]
[0, 4, 16, 36, 64]

Examples

>>> vec=[2,4,6]
>>> [3*x for x in vec]
[6, 12, 18]

>>> [3*x for x in vec if x>3]
[12, 18]

>>> [3*x for x in vec if x<2]
[]

>>> [[x,x**2] for x in vec]
[[2, 4], [4, 16], [6, 36]]

>>> [x,x**2 for x in vec] # error - need () for tuples
File "<stdin>", line 1
[x,x**2 for x in vec]
^
SyntaxError: invalid syntax

>>> [(x,x**2) for x in vec ]
[(2, 4), (4, 16), (6, 36)]

>>> vec1=[2,4,6]
>>> vec2=[4,3,-9]
>>> [x*y for x in vec1 for y in vec2]
[8, 6, -18, 16, 12, -36, 24, 18, -54]

>>> [x+y for x in vec1 for y in vec2]
[6, 5, -7, 8, 7, -5, 10, 9, -3]

>>> [vec1[i]*vec2[i] for i in range(len(vec1))]
[8, 12, -54]

List comprehensions are more flexible than map() and can be applied to complex expressions and nested functions.
Example
>>> [str(round(355/113.0,i)) for i in range(1,6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']

In list comprehension list contain any type of elements including strings, nested lists and functions

Example
>>> words='The quick brown fox jumps over the lazy dog'.split()
>>> print words
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
>>>
>>> stuff=[[w.upper(),w.lower(),len(w)] for w in words]
>>> for i in stuff:
... print i
...
['THE', 'the', 3]
['QUICK', 'quick', 5]
['BROWN', 'brown', 5]
['FOX', 'fox', 3]
['JUMPS', 'jumps', 5]
['OVER', 'over', 4]
['THE', 'the', 3]
['LAZY', 'lazy', 4]
['DOG', 'dog', 3]
>>>
>>> stuff=map(lambda w: [w.upper(),w.lower(),len(w)],words)
>>> for i in stuff:
... print i
...
['THE', 'the', 3]
['QUICK', 'quick', 5]
['BROWN', 'brown', 5]
['FOX', 'fox', 3]
['JUMPS', 'jumps', 5]
['OVER', 'over', 4]
['THE', 'the', 3]
['LAZY', 'lazy', 4]
['DOG', 'dog', 3]

This example shows that, we can do the same thing by using the map() and lambda function. But in most cases we use the list comprehension, because it is more efficient and easier to read.

Sunday 3 July 2011

Exception and Exception handling in python

    Exceptions are general programming technique for altering the regular program flow in special cases such as errors or incorrect input.
     Like many other programming languages, python has exception handling via try...except blocks. Python uses try ... except to handle exceptions and raise to generate them. Java and C++ use try ...catch to handle exceptions, and throw to generate them. 
Exceptions
Exceptions are errors, that are detected during the execution of code. In this post I want to explain how we can handle this types of exceptions. Most exceptions are not handled by programs. In such situations we can generate an error message.
Various types of exceptions are ZeroDivisionError,NameError and TypeError.
Example for ZeroDivisionError
>>> 20*(2/0)
Output
ZeroDivisionError: integer division or modulo by zero
Here we try to divide 2 by zero, this is an example for ZeroDivisionError.

Example for NameError
>>> 5+spam*3
Output
NameError: name 'spam' is not defined
Example for TyeError
>>> '6'+3
Output
TypeError: cannot concatenate 'str' and 'int' objects
Exception Handling
    We can catch or handle an exception which a piece of code may generate by putting that piece of code inside of a try block and then specifying corresponding except block.
Example
>>> try:
... some_func()
... except:
... print 'Caught an exception in "some_func()".Exiting.'
... exit(1)
...
Caught an exception in "some_func()".Exiting.
In this example function 'some_func()' generate an error, here we write this function in try block, corresponding solutions are write in the except block.
Multiple except blocks may be associated with a given try block. The first except which matches the type of exception raised will be executed.
Example
>>> try:
... some_func()
... except FoolException,e:
... print 'Caught a FoolException. Exiting.'
... exit(1)
... except RuntimeError,e:
... print 'Caught a RuntimeError. Exiting.'
... exit(10)
... except:
... print 'caught an exception in "some_func()". Exiting'
... exit(100)
Raising Exceptions
The raise statement allows the programmer to force a specified exception to occur.
Example
>>> foo=56
>>> if foo==56: raise RuntimeError("Can't continue - foo is 56")
Output
RuntimeError: Can't continue - foo is 56
finally
There may be some code (like closing a file) that you need to execute no matter whether the code before that raises an exception or runs smoothly. We can put such code in finally block.
Example
>>> fname='file-name.txt'
>>> try:
... f=file(fname)
... except IOError:
... print "File %s could not be opened for reading. Closing."% fname
... exit(1)

>>> try:
... process_file(f)
... finally:
... f.close()
In this example first uses a try block to safely open a file for reading and then uses a try and finally to ensure that the file gets closed.