Popular Posts

Saturday, July 6, 2013

Simple Peg Solitaire Game in Python



Description:

   It is a Simple Peg Solitaire command line game in python. It has two classes Board and Play.
When create Object for Board class it initialize game board like the above picture. Board class contain methods to display board and check any valid move have in this board.

        Player Class methods get the move positions from the user and validate positions, play with the game with user entered date it valid.

Main function plays the game with the Board and Player classes.

 




 """Pige Solatire  Game"""

PEG = 'O'
BLANK = '#'
HOLE = ' '

class Board:
    """ This class is responsible to create board and checking board status"""

    def __init__(self):
        """ Initialize Board and it's attributes"""

        self.move = 0
        self.max_row = 7
        self.max_col = 7
        self.max_move = 31
        self.board = []
        self.board.append([BLANK, BLANK, PEG, PEG, PEG, BLANK, BLANK])
        self.board.append([BLANK, BLANK, PEG, PEG, PEG, BLANK, BLANK])
        self.board.append([PEG, PEG, PEG, PEG, PEG, PEG, PEG])
        self.board.append([PEG, PEG, PEG, HOLE, PEG, PEG, PEG])
        self.board.append([PEG, PEG, PEG, PEG, PEG, PEG, PEG])
        self.board.append([BLANK, BLANK, PEG, PEG, PEG, BLANK, BLANK])
        self.board.append([BLANK, BLANK , PEG, PEG, PEG, BLANK, BLANK])
      
    def print_board(self):
        """ Display current status of board """

        print '\nBoard:\n'
        print "  0 1 2 3 4 5 6"
        print "---------------"
        count = 0
        for row in self.board:
            print ("%d") % (count),
            count += 1
            for position in row:
                print position,
            print ''
  
    def check_move_possible(self):
        """ Check for further valid move in the board"""

        for i in range(self.max_row):
            if(i < 2 or i > 4):
                ret = self.three_row_check(i)
            else:
                ret = self.seven_row_check(i)
            if(ret == True):
                return True

        for i in range(self.max_col):
            if(i < 2 or i > 4):
                ret = self.three_col_check(i)
            else:
                ret = self.seven_col_check(i)
                if(ret == True):
                    return True
        return False
                          
    def three_row_check(self, row):
        """ Checking valid move in three column rows"""
      
        if(self.board[row][2] == PEG and self.board[row][3] == PEG
           and self.board[row][4] == HOLE):
            return True

        if(self.board[row][2] == HOLE and self.board[row][3] == PEG
           and self.board[row][4] == PEG):
            return True
        return False

    def seven_row_check(self, row):
        """ Checking valid move in seven column rows"""
      
        for i in range(self.max_col):
            if(i == 0):
                if(self.board[row][0] == PEG and self.board[row][1] == PEG \
                       and self.board[row][2] == HOLE):
                    return True
            elif(i == 6 or i == 5):  
                if(self.board[row][6] == PEG and self.board[row][5] == PEG \
                       and self.board[row][4] == HOLE):
                    return True
            else:
                if(self.board[row][i] == PEG and self.board[row][i + 1] == PEG):
                    if(self.board[row][i - 1] == HOLE or \
                           self.board[row][i + 2] == HOLE):
                        return True
        return False

    def three_col_check(self, col):
        """ Checking valid move in three row cols"""
      
        if(self.board[2][col] == PEG and self.board[3][col] == PEG \
               and self.board[4][col] == HOLE):
            return True

        if(self.board[2][col] == HOLE and self.board[3][col] == PEG \
               and self.board[4][col] == PEG):
            return True
        return False

    def seven_col_check(self, col):
        """ Checking valied move in seven row cols"""
      
        for i in range(self.max_row):
            if(i == 0):
                if(self.board[0][col] == PEG and self.board[1][col] == PEG \
                       and self.board[2][col] == HOLE):
                    return True
            elif(i == 6 or i == 5):  
                if(self.board[6][col] == PEG and self.board[5][col] == PEG \
                       and self.board[4][col] == HOLE):
                    return True
            else:
                if(self.board[i][col] == PEG and self.board[i + 1][col] == PEG):
                    if(self.board[i - 1][col] == HOLE or \
                           self.board[i + 2][col] == HOLE):
                        return True
        return False
  

  
class Play:
    """ This class is responsible to get move info \
    from player and play peg solitaire game."""

    def __init__(self):

        "initialize instance variables"
        self.get_row = 0
        self.get_col = 0
        self.put_row = 0
        self.put_col = 0
        self.midr = 0
        self.midc = 0

    def get_pos(self):
        """ Get move position from user"""

        self.get_row = int (raw_input("Enter row no to get peg : "))
        self.get_col = int (raw_input("Enter col no to get peg : "))
        self.put_row = int (raw_input("Enter row no to put peg : "))
        self.put_col = int (raw_input("Enter col no to put peg : "))
      
    def validate_pos_board(self):
        """ Validate user entered position inputs with board layout"""

        if(self.get_row < 0 or self.get_row > 6):
            return False

        if(self.get_col < 0 or self.get_col > 6):
            return False

        if(self.put_row < 0 or self.put_row > 6):
            return False
      
        if(self.put_col < 0 or self.put_col > 6):
            return False
        return True

    def validate_valied_pos(self):
        """ validate user entered positions """

        if(self.get_row == self.put_row):
            val = self.get_col - self.put_col
            if(val == -2 or val == 2):
                self.midr = self.get_row
                self.midc = (self.get_col + self.put_col) / 2
                return True
        if(self.get_col == self.put_col):
            val = self.get_row - self.put_row
            if(val == -2 or val == 2):
                self.midr = (self.get_row + self.put_row) / 2
                self.midc = self.get_col
                return True
        return False
          
    def validate_pos_with_peg_and_play(self, board):
        """ Valid date user entered position with valid move"""

        if(board.board[self.get_row][self.get_col] == PEG):
            if(board.board[self.put_row][self.put_col] == HOLE):
                if(board.board[self.midr][self.midc] == PEG):
                    board.board[self.get_row][self.get_col] = HOLE
                    board.board[self.put_row][self.put_col] = PEG
                    board.board[self.midr][self.midc] = HOLE
                    board.move += 1
                    return True
                return False
            return False

def main():
    """ Function for playing Peg Solitaire """
    play_board = Board()
    player = Play()
  
    while(True):
        play_board.print_board()
        player.get_pos()
      
        ret = player.validate_pos_board()
        if(ret == False):
            print "Wrong Position"
            continue
      
        ret = player.validate_valied_pos()
        if(ret == False):
            print "Wrong Position"
            continue
      
        ret = player.validate_pos_with_peg_and_play(play_board)
        if(ret == False):
            print "Wrong Position"
            continue
      
        ret = play_board.check_move_possible()
        if(ret == False):
            print "No more legal Moves"
            play_board.print_board()
            break
      
        if(play_board.move == play_board.max_move):
            print "Congratulations!! you have solved the puzzle!"
            play_board.print_board()
            break

if __name__ == '__main__':
    main()
  

Wednesday, February 22, 2012

Matrix Chain Multiplication

Code:


import java.util.Scanner;


public class MatricsChainMul {
    public static void main(String[] args) {
        int m[][];
        int s[][];
        int mat_count;
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter how many no of matrices to calculate");
        mat_count = scan.nextInt();
        mat_count++;
        int r[] = new int[mat_count];
        int c[] = new int[mat_count];
        m = new int[mat_count][mat_count];
        s = new int[mat_count][mat_count];
   
        for(int i = 1;i < mat_count;i++){
            System.out.println("Enter "+i+" matrix rows and cols");
            r[i] = scan.nextInt();
            c[i] = scan.nextInt();
        }
       
       
        c[0] = r[1];
       
        for(int i = 1; i < mat_count;i++){
            for(int j = 1; j < mat_count; j++)
            m[i][j] = 0;
        }
       
       
        int count = mat_count - 1;
        int a = 1;
        int temp = 0;
       
        while(count > 0){
            for(int i = 1; i < count; i++){
                int j = i + a;
                for(int k = i; k < j; k++){
                    temp = m [i][k] + m[k+1][j] + (c[i-1] * c[k] * c[j]);
                    if(m[i][j] == 0 || m[i][j] > temp){
                        m[i][j] = temp;
                        s[i][j] = k;
                    }
                }
               
            }
                count--;
                a++;
        }
        System.out.println("\n------------M Matrix------------");
        print(m, mat_count - 1);
        System.out.println("\n------------S Matrix------------");
        print(s, mat_count-1);
       
    }   
   
   
    static void print(int mat[][], int c) {
       
        int row = 1;
        int col = c;
        int i = row,j= col;
        while(true){
            System.out.print(mat[i][j]+"\t");
            if(j == col){
                System.out.println();
                j = col - i;
                i = row;
            }else{
                i++;
                j++;
            }
            if(i == col)
                break;
           
        }
       
    }
   

}


Largest Common Subsequence

Code:


public class LCS {
    static String str1, str2;
    static int m, n, c[][];
    static char b[][];
   
    public static void main(String[] args) {
   
    if(args.length != 2){
        System.out.println("It should take Two Strings");
        System.exit(0);
    }
    str1 = args[0];
    str2 = args[1];
    m = str1.length();
    n = str2.length();
    m++;
    n++;
    c = new int[m][n];
    b = new char[m][n];
    c[0][0] = 0;
   
    for(int i = 1; i < m ; i++)
        c[i][0] = 0;
   
    for(int j = 0; j < n; j++)
        c[0][j] = 0;
   
    for(int i = 1; i < m ; i++) {
        for(int j = 1; j < n; j++) {
        if(str1.charAt(i-1) == str2.charAt(j-1)) {
            c[i][j] = c[i-1][j -1] + 1;
            b[i][j] = 'S';
        } else if(c[i-1][j] >= c[i][j-1]) {
            c[i][j] = c[i-1][j];
            b[i][j] = 'U';
        } else {
            c[i][j] = c[i][j-1];
            b[i][j] = 'D';
        }
        }
    }
    System.out.println("-----------------C Array------------");
   
    for(int i = 0; i < m ; i++) {
        for(int j = 0; j < n; j++) {
        System.out.print(c[i][j] + " ");
        }
       
        System.out.println();
       
    }
   
    System.out.println("-----------------B Array------------");
   
    for(int i = 1; i < m ; i++) {
        for(int j = 1; j < n; j++) {
        System.out.print(b[i][j] + " ");
        }
       
        System.out.println();
       
    }
   
    print_LCS(b,m-1,n-1);   
   
    }
   
   
    static void print_LCS(char b[][],int m ,int n){
    if(m == 0 || n == 0)
        return;
    if(b[m][n] == 'S') {
        print_LCS(b, m-1, n-1);
        System.out.print(str1.charAt(m-1));
    } else if (b[m][n] == 'U') {
        print_LCS(b, m-1, n);
    } else {
        print_LCS(b, m, n-1);
    }
   
    }
}

Counting Sort

Code:

#include <stdio.h>
#include <stdlib.h>

int findbig (int *, int size);
int
main ()
{
  int length, big;
  int *a, *c, *b;
  int j, i;

  printf ("Enter the length of the Array to be sorted:");
  scanf ("%d", &length);
  a = (int *) malloc (sizeof (int) * (length + 1));
  b = (int *) malloc (sizeof (int) * (length + 1));
  printf ("\n Enter the elements one by one");
  for (i = 1; i <= length; i++)
    scanf ("%d", &a[i]);
  big = findbig (a, length);
  c = (int *) malloc (sizeof (int) * (big + 1));
  for (j = 0; j <= big; j++)
    c[j] = 0;

  for (j = 0; j <= length; j++)
    b[j] = 88;

  for (j = 1; j <= length; j++)
    c[a[j]] = c[a[j]] + 1;


  printf ("\n C Array after  c[a[j]] = c[a[j]] + 1\n");
  for (j = 0; j <= big; j++)
    printf ("%d \t", c[j]);
  printf ("\n");

  for (j = 1; j <= big; j++)
    c[j] = c[j] + c[j - 1];

  printf ("\n C Array after   c[j] = c[j] + c[j-1]\n");
  for (j = 0; j <= big; j++)
    printf ("%d \t", c[j]);
  printf ("\n");

  for (j = length; j >= 1; j--)
    {
      b[c[a[j]]] = a[j];
      c[a[j]] = c[a[j]] - 1;
      printf ("\nAfter j = %d\n ", j);
      printf ("B array:");
      for (i = 1; i <= length; i++)
    printf ("%d \t", b[i]);
      printf ("\n C Array:");
      for (i = 0; i <= big; i++)
    printf ("%d \t", c[i]);
      printf ("\n");

    }

  free (a);
  free (b);
  free (c);


}


int findbig (int *array, int size)
{
  int big, i;
  big = array[1];
  for (i = 2; i <= size; i++)
    {
      if (array[i] > big)
    big = array[i];
    }
  return big;
}

Monday, February 13, 2012

Simple Chatting Program in Java

   This article explain how to write simple chatting GUI program in java using Socket. I use MigLayout for Layout Manager. It is a simple third party java layout , you can download it from miglayout-3.7-swing.jar or It is available with my project Files.

System Setup:
   Install JDK 1.4 or above JDK versions in your Windows or Linux Systems.
   

Running APPS:
Runnig Server  side System:
  Download  Server files for server side communication.

  In Windows:

  • Open command prompt.
  • Goes to the directory (folder) where you save the project and type the below commands.
  • javac -cp ;miglayout-3.7-swing.jar ServerGUI.java 
       for comipling the project.
  • java -cp ;miglayout-3.7-swing.jar ServerGUI for Running project.


In Linux:
  • Open terminal window.
  • Goes to the directory (folder) where you save the project and type the below commands.
  • export CLASSPATH =${CLASSPATH}:(path of the jar file with .jar extension).
  • javac  ServerGUI.java   for compilation.
  • java  ServerGUI   for Runing the project.


 It asks  your name, After enter  your name ,System waiting for client request, If any request received from client, The server accept and shows the frame for communication.


Runnig Client side System:
      Download  Client  files for server side communication. 

   Make sure you run Server App in one system in the Network before run Client App.
Commands:
  In Windows:
  • Open command prompt.
  • Goes to the directory (folder) where you save the project and type the below commands.
  • javac -cp ;miglayout-3.7-swing.jar ClientGUI.java   for compilation.
  •  java -cp ;miglayout-3.7-swing.jar ClientGUI   for Runing the project.



In Linux:
  • Open terminal window.
  • Goes to the directory (folder) where you save the project and type the below commands.
  • export CLASSPATH =${CLASSPATH}:(path of the jar file with .jar extension).
  • javac  ClientGUI.java   for compilation.
  • java  ClientGUI  for Runing the project.

    It asks the server IP address and your name, After enter  IP address and your name the frame appear on the screen, Now you are ready to chat.

Testing in a Single System in Network:
   It is also possible to test the Server and Client Apps in the same System using the above procedures,
If you connected in an Network.

Testing in a Single System with out  Network Connection:
 Normally there is a IP Address 127.0.0.1 for Loop back connection, use this IP address .




Thursday, December 15, 2011

GETTING BUS TIMING UPDATE THROUGH SMS(USING PYTHON)


    In this modernized world SMS is one thing  which is useful in getting regular updates and information easily.
This simple project is used to get update of  bus timing through SMS.

GSM Modem (Global System for Mobile communication):
     GSM modem is a device in mobile communication for data transfer(SMS, Cal). Many GSM Modems available in  market, for our project, We use GSM Modem with serial port for sending and receiving SMS in PC using AT commands.

Requirements:

Hardware:
 *  A GSM Modem with serial port cable.
 *  PC.
 *  A Valied SIM card for communication.

Software:
 * Python 2.7,  Pyserial module for serial communication, MySQLdb module for (MYSQL data base   connectivity)
 * MySQL Database


Sample Testing:
 * Create a database(DB) named 'bus' in MySQL and in that DB create a table names 'route'
     with unnecessary fields route, time1, time2, time3 as varchar type.
 * insert values into table 'route'.
 * insert SIM card in modem and connect to the PC.
 * Run the below python code in our PC.
 * Send SMS in format, TIME<space> <route> from another mobile to the SIM which you insert in
    GSM   Modem.
  *  If you send correct route the code fetch data from the 'route' table those match from the received route
     and send back to you.
 * In case the format is wrong or wrong route it send info accordingly.

Code:
import serial
import MySQLdb


def send_sms(ser,no,sms):
    ser.write("AT+CMGS="+no+"\r")
    ch = ser.readline()
    ch = ch.strip()
    while ch != ">":
        ch = ser.readline()
        ch = ch.strip()
    ser.write(sms+"\x1A")
    ser.readline()
    sucess = ser.readline()
    if sucess == "OK":
        print "SMS send:" + sms
    else:
        print "Failed to send"
              
def delete_sms(ser,loc):
    ser.write("AT+CMGD="+str(loc)+",4\r")
    ser.readline()
    while True:
        if ser.readline() == "OK":
            break

    print "SMS Deleted sucessfully"

def open_db(dbname):
    conn = MySQLdb.Connection( host="localhost", user="root", passwd="password", db=dbname)
    print "connection object ready"
    mysql = conn.cursor()
    print "cursor object ready"
    return mysql

def modem_init():
    ser = open_serial("/dev/ttyUSB0")
    while True:
        ser.write("AT+CMGF=1\r")
        ser.readline()
        if ser.readline() == "OK":
            break
    while True:    
        ser.write("AT+CNMI=1,1,0,0,0\r")
        ser.readline()
        if ser.readline() == "OK":
            break
       
    print "modem ready for communication"
    return ser

def open_serial(port):
    ser = serial.Serial(port,9600,timeout=2)
    print "serial port opend"
    return ser

   
try:
    ser = modem_init()
    mysql = open_db("bus")
    while True:
        ms = ser.readline()
        m = ms.split(":")       
        if m[0] == "+CMTI":
            print "SMS received"
            m = ms.split(",")
            ser.write("AT+CMGR="+m[1]+"\r")
            ser.readline()
            ms = ser.readline()
            content = ser.readline()
            ser.readline()
            m = ms.split(",")
            no = m[1]
            print "Mobile NO:"+ no
            content = content.upper()
            content = content.strip()
            print "Content:"+ content
            time = content.split(" ")
            if time[0] == "TIME":
                if time[1] != " ":
                    query = "select * from route where route = '"+ time[1] +"'"
                    mysql.execute(query)
                    resultset = mysql.fetchall()
                    if resultset == ():
                        sms = "wrong route"
                        send_sms(ser, no, sms)
                        delete_sms(ser, 1)
                       
                    else:
                        sms = "%s %s %s %s"% resultset[0]
                        print sms
                        send_sms(ser, no, sms)
                        delete_sms(ser, 1)
                else:
                    sms = "Wrong format TIME<space>ROUTE no route"
                    send_sms(ser, no, sms)
                    delete_sms(ser, 1)
                   
            else:
                sms = "Wrong format TIME<space>ROUTE"
                send_sms(ser, no, sms)
                delete_sms(ser, 1)
finally:
    ser.close()
   

   

Wednesday, December 7, 2011

Simple Template Inheritance (Multiplication of two Matrices)

/* This is a simple matrix multiplication program
 * using Template inheritance.It take rows and columns of
 * two matrixes and dynamically create matrices arr1 and arr2
 * accoriding to the rows and columns user given
 * and finally add matrices arr1 and arr2 and show
 * the results i terminal.  
 */


#include <iostream>

using namespace std;

/* Template class First */
template<class T>
class First{
protected:
  int r1,c1;
  T **arr1;
 
public:
  /* First class constructor */
  First(int x,int y):r1(x),c1(y){
    arr1 = new T*[c1];
    for(int i = 0; i < r1; i++ )
      arr1[i] = new T[r1];
  }
};

/* Template class Second */
template<class T>
class Second{
protected:
  int r2,c2;
  T **arr2;
 
public:
  /* Second class constructor */
  Second(int x,int y):r2(x),c2(y){
    arr2 = new T*[c2];
    for(int i = 0; i < r2; i++ )
      arr2[i] = new T[r2];
   
  }
};

/* This class Result inherit the template classes
 * First and Second.
*/
template<class T>
class Result:public First<T>,public Second<T>{
public:
  Result(int x, int y, int c, int d):First<T>(x,y),Second<T>(c,d){
  }

  /* This getvalue function get values from the user
   * for the two matrices arr1 and arr2.
   */
  void getvalue()
  {
    cout<<"\nEnter Matrix1 elements one by one:\n";
    for(int i = 0; i < First<T>::r1; i++ )
      for(int j = 0; j < First<T>::c1; j++)
    cin >> First<T>::arr1[i][j];
   
    cout<<"\nEnter Matrix2 elements one by one:\n";
    for(int i = 0; i < Second<T>::r2; i++ )
      for(int j = 0; j < Second<T>::c2; j++)
    cin >> Second<T>::arr2[i][j];
   
  }
 
  /* This print function print the matrices*/
  void print(){
    cout<<"\n--------Matrix1 elements ---------\n";
    for(int i = 0; i < First<T>::r1; i++ ){
      for(int j = 0; j < First<T>::c1; j++)
    cout << First<T>::arr1[i][j]<<"\t";
      cout<<"\n";
    }
   
    cout<<"\n--------Matrix2 elements ---------\n";
    for(int i = 0; i < Second<T>::r2; i++ ){
      for(int j = 0; j < Second<T>::c2; j++)
    cout << Second<T>::arr2[i][j]<<"\t";
      cout<<"\n";
    }
   
  }

  /* This function multiply two matrices arr1 and arr2 and display
   * the result.  
   */
  void multiply()
  {
    if(First<T>::c1 == Second<T>::r2){
      cout<<"\nResultant Matrix after multiplication\n";
      T x ;
      for(int i = 0; i < First<T>::r1; i++){
    for(int j = 0; j < Second<T>::c2; j++){
      x = 0;
      for(int k = 0; k < First<T>::c1; k++)
        x += First<T>::arr1[i][k] * Second<T>::arr2[k][j];
      cout<<x<<"\t";
    }
    cout<<"\n";
      }
    }else{
      cout<<"Wrong Matrixes for multiplication \n pls cheke rows and colums of the two matxices";
    }
  }
 
};

int main()
{
  int x,y,c,d;
  cout<<"\nEnter Matrix1 row and col:";
  cin>>x>>y;
  cout<<"\nEnter Matrix2 row and col:";
  cin>>c>>d;
  Result<float> Rs(x,y,c,d);
  Rs.getvalue();
  Rs.print();
  Rs.multiply();
  getch();
}