Wednesday, November 23, 2011

Snake And Ladders Game Code in java


Snake and Ladder game code in java.

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.net.*;
import java.io.*;

class Main implements ActionListener,MouseListener
{
 JFrame f;
 JTabbedPane tabPane;
 JPanel mainPanel,introPanel,gamePanel,playerPassPanel,diePanel; 
 JPanel gameCenter,gameEast,gameWest,gameNorth,gameSouth;
 Icon p1,p2,header;
 Icon up,down;
 Icon icon[][]= new Icon[10][10];
 Icon winericon[][]= new Icon[10][10];
 Icon dieIcon;
 JButton introB[]= new JButton[5];
 JButton b[][]=new JButton[10][10];
 JButton start,restart;
 JButton JBplayer,JBcomputer;  
JLabel die;
Random randomNo;
 int imageFlag;
 int i,j,num;
 int prevIp1,prevJp1;
 int path;
 int p1value,p2value;
 int player,computer;
 int gameover;
 int cimageFlag=0;
 int cnoFlag=0;
 String str;
  int n[][]={ { 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},
{50,51,52,53,54,55,56,57,58,59},
{60,61,62,63,64,65,66,67,68,69},
{70,71,72,73,74,75,76,77,78,79},
{80,81,82,83,84,85,86,87,88,89},
{90,91,92,93,94,95,96,97,98,99},
 };

 int game[][]={
      {100,99,98,97,96,95,94,93,92,91},
       {81,82,83,84,85,86,87,88,89,90},
{80,79,78,77,76,75,74,73,72,71},
{61,62,63,64,65,66,67,68,69,70},
{60,59,58,57,56,55,54,53,52,51},
{41,42,43,44,45,46,47,48,49,50},
{40,39,38,37,36,35,34,33,32,31},
{21,22,23,24,25,26,27,28,29,30},
{20,19,18,17,16,15,14,13,12,11},
{ 1, 2, 3, 4, 5, 6, 7, 8, 9,10},
     };
int winer[][]={
{ 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,50},
{51,52,53,54,55,56,57,58,59,60},
{61,62,63,64,65,66,67,68,69,70},
{71,72,73,74,75,76,77,78,79,80},
{81,82,83,84,85,86,87,88,89,90},
{91,92,93,94,95,96,97,98,99,100},
     };
 Main()
 {

 f= new JFrame("Snakes and Ladders 1.0");
 f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 mainPanel= new JPanel();
 tabPane =new JTabbedPane(JTabbedPane.LEFT);
 f.setLayout(new BorderLayout());
 for(int i=0;i<introB.length;i++)
  {
introB[i]= new JButton(Integer.toString(i));
}

 randomNo= new Random();

 JBplayer= new JButton("player1");
 JBcomputer= new JButton("player2");

 JBplayer.setEnabled(false);
 JBcomputer.setEnabled(false);

 JBplayer.addActionListener(this);
 JBcomputer.addActionListener(this); 
 die = new JLabel();
game();
introduction();
 f.add(tabPane,BorderLayout.CENTER);
 f.setResizable(false);
   f.setSize(750,700);
 //f.pack();
  f.setVisible(true);
  }

void introduction()
{

 introPanel= new JPanel();
  
 JPanel main= new JPanel();
 JLabel l1= new JLabel();
 //JPanel about= new JPanel(); 
  
       
 JLabel l2=new JLabel("<html><body><Font color='red' Size='14'> Hi,</Font><Font color='green' Size='4'>every one this is Snake and Ladders version 1.0 , plz mail if u find any type of problem/error and ur sugession.<br></Font> <Font color='red' Size='3'>thank you visit for more Programs:</Font>  <Font color='gray' Size='6'>gauravsiwach.blogspot.com</Font> </body></html>");


 Icon mypic;

 mypic=new ImageIcon("images/itsme.jpg");         

 l1.setIcon(mypic);

 introPanel.setLayout(new BorderLayout()); 
 introPanel.add(l1,BorderLayout.CENTER); 
 l2.addMouseListener(this);
 l2.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
 introPanel.add(l2,BorderLayout.SOUTH); 
 tabPane.addTab("About me",introPanel);
}

void game()
{
 JLabel gameheader= new JLabel();
 JLabel logo = new JLabel(); 
 JLabel l1= new JLabel(); 
 JLabel l2= new JLabel(); 

 restart= new JButton("Restart");
 restart.setEnabled(false);
 restart.addActionListener(this);

 start= new JButton("Start");
 start.addActionListener(this);

 gamePanel= new JPanel();


 gameCenter=new JPanel();
 gameWest= new JPanel();
 gameNorth=new JPanel();
 gameSouth= new JPanel();

  gameCenter.setLayout(new GridLayout(10,10));
  gameEast= new JPanel(new GridLayout(2,1));

  gameWest.setLayout(new FlowLayout());
 gameNorth=new JPanel(new FlowLayout());
 gameSouth= new JPanel(new FlowLayout());

 gamePanel.setLayout(new BorderLayout());

 p1= new ImageIcon("images/p1.gif");        
 p2= new ImageIcon("images/p2.gif");       
 up= new ImageIcon("images/up.gif");
 down= new ImageIcon("images/down.gif");

 l1.setIcon(p1);
 l2.setIcon(p2);

 header=new ImageIcon("images/header.jpg");        
 gameheader.setIcon(header);
  
  for(int i=0;i<10;i++)
for(int j=0;j<10;j++)
{
b[i][j]= new JButton();
        //b[i][j].addActionListener(this);        
path=game[i][j];
str=Integer.toString(path);
icon[i][j]=new ImageIcon("images/"+str+".jpg");
       b[i][j].setIcon(icon[i][j]);
                 
}

for(int i=0;i<10;i++)
for(int j=0;j<10;j++)
{
path=winer[i][j];
str=Integer.toString(path);
winericon[i][j]=new ImageIcon("images/winer/"+str+".jpg");
                        // b[i][j].setIcon(winericon[i][j]);
}
 str=Integer.toString(1);
 dieIcon= new ImageIcon("images/Game dies/"+str+".jpg");
 die.setIcon(dieIcon);
 gameSouth.add(l1); 
 gameSouth.add(JBplayer);
 gameSouth.add(die);
 gameSouth.add(JBcomputer); 
 gameSouth.add(l2); 

 gameNorth.add(start);
 gameNorth.add(gameheader);
 gameNorth.add(restart);
  
  for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
gameCenter.add(b[i][j]);

              //System.out.print("["+i+"]["+j+"],");
                
}
//System.out.println();
}
 gamePanel.add(gameCenter,BorderLayout.CENTER);
 gamePanel.add(gameWest,BorderLayout.WEST);
 gamePanel.add(gameNorth,BorderLayout.NORTH);
 gamePanel.add(gameSouth,BorderLayout.SOUTH);

  tabPane.addTab("Game",gamePanel);
  
}

void chance()
{
 int n=randomNo.nextInt(3);
 int i=0;

 //System.out.println("Chacne is :"+n) ;
 if(n==0)
chance();

 if(n==1)
{
player=1;
computer=0;
}
  else if(n==2)
{
player=0;
  computer=1;
}

  if(n==1)
{
JBcomputer.setEnabled(false);
JBplayer.setEnabled(true);
    
}
 else if(n==2)
{
JBcomputer.setEnabled(true);
JBplayer.setEnabled(false);
    
  }
}

public void actionPerformed(ActionEvent e)
{

 int n=0;
try{
 if(e.getSource()==JBplayer)
{

  //System.out.println("JB Player");
do{
n =playerPassNumber();
}while(n==0);

//System.out.println("UR playerPass value is :"+n);        
p1value=p1value+n;
         
if(p1value>=100)
{
p1value=100;
}
 
playerimageTraval(p1value);

JBcomputer.setEnabled(true);
JBplayer.setEnabled(false);
setBothImage();
  }
  else if(e.getSource()==JBcomputer)
{
//System.out.println("JB Computer");
do{
n =playerPassNumber();
}while(n==0);

//System.out.println("Computer Pass Value is "+n);
p2value=p2value+n;
if(p2value>=100)
{
p2value=100;
}
computerimageTraval(p2value);
JBcomputer.setEnabled(false);
JBplayer.setEnabled(true);

setBothImage();
}
  else if(e.getSource()==restart)
{
  p1value=0;
p2value=0;

cnoFlag=0;
cimageFlag=0;

chance();
rePrint();
}
  else if(e.getSource()==start)
{
gameover=0;
p1value=0;
p2value=0;
cnoFlag=0;
cimageFlag=0;
rePrint();
 start.setEnabled(false);
 restart.setEnabled(true);
 chance();
}
else
{
imageChange(e);
}
}catch(Exception ee)
{
//System.out.println("Error in BUTTON:"+ee);
}
}
int playerPassNumber()
{
 int i= randomNo.nextInt(7);

         str=Integer.toString(i);
dieIcon= new ImageIcon("images/Game dies/"+str+".jpg");
die.setIcon(dieIcon);

     return i;

}

void winerdraw()
{
int i=0;
start.setEnabled(true);
restart.setEnabled(false);
JBplayer.setEnabled(false);
JBcomputer.setEnabled(true);
JBcomputer.setEnabled(false);
 
for(int k=0;k<10;k++)
for(int l=0;l<10;l++)
{
gameover=1;
         b[k][l].setIcon(winericon[k][l]);             
}

    
}


void rePrint()
{
try{

for( i=0;i<10;i++)
{
for(j=0;j<10;j++)
 {
   // b[i][j].setIcon(null);
b[i][j].setIcon(icon[i][j]);
 }
}

   }catch(Exception e)
{
//System.out.println("error in repaint"+e);
}

}

void playerimageTraval(int n)
{
int i=j=0;
int imageFlag=0;
int noFlag=0;

if(gameover==0)
{
try{
rePrint();
 for(i=0;i<10;i++)
      {
for(j=0;j<10;j++)
{
if(n==game[i][j])
   {
                noFlag=1;
break;
   }
}
  if(noFlag==1)
break;
      }

   if(noFlag==1)
{
if(imageFlag==0)
{
Thread.sleep(200);
b[i][j].setIcon(p1);
imageFlag=1;
prevIp1=i;
prevJp1=j;
       }
        else
{
path=game[prevIp1][prevJp1];
str=Integer.toString(path);
  Thread.sleep(200);
icon[prevIp1][prevJp1]=new ImageIcon("images/"+str+".jpg");
Thread.sleep(200);
       b[prevIp1][prevJp1].setIcon(icon[prevIp1][prevJp1]);
b[i][j].setIcon(p1);
prevIp1=i;
prevJp1=j;
       }

/*****************checks for staires**********************/
if(n==10)
{
n=28;
playerimageTraval(n);
p1value=n;
}
else if(n==17)
{
n=37;
playerimageTraval(n);
p1value=n;
}
else if(n==31)
{
n=70;
playerimageTraval(n);
p1value=n;
}
else if(n==45)
{
n=84;
playerimageTraval(n);
p1value=n;
}
else if(n==78)
{
n=97;
playerimageTraval(n);
p1value=n;
}


/*****************Checks for Snakes***************************/
if(n==95)
{
        n=73;
playerimageTraval(n);
p1value=n;
}
else if(n==79)
{
        n=59;
playerimageTraval(n);
p1value=n;
}
else if(n==68)
{
        n=48;
playerimageTraval(n);
p1value=n;
}
else if(n==44)
{
        n=21;
playerimageTraval(n);
p1value=n;
}
else if(n==34)
{
        n=16;
playerimageTraval(n);
p1value=n;
}

}

if(n>=100)
{   
//System.out.println("Congr u r win");
winerdraw();

}
}
catch(Exception e)
{

}
}

}

void setBothImage()
{
int i=0;
int j=0;
int noFlag=0;

if(gameover==0)
{
for(i=0;i<10;i++)
      {
for(j=0;j<10;j++)
{
if(p1value==game[i][j])
   {
                                noFlag=1;
break;
   }
}
  if(noFlag==1)
break;
      }

if(noFlag==1)
{
b[i][j].setIcon(p1);  
}

noFlag=0;

for(i=0;i<10;i++)
      {
for(j=0;j<10;j++)
{
if(p2value==game[i][j])
   {
                                noFlag=1;
break;
   }
}
  if(noFlag==1)
break;
      }

if(noFlag==1)
{
b[i][j].setIcon(p2);
}
}
}


void computerimageTraval(int n)
{
int i=j=0;
int imageFlag=0;
int noFlag=0;

try{
rePrint();
 for(i=0;i<10;i++)
      {
for(j=0;j<10;j++)
{
if(n==game[i][j])
   {
                noFlag=1;
break;
   }
}
  if(noFlag==1)
break;
      }

  if(noFlag==1)
{
if(imageFlag==0)
{
Thread.sleep(200);
b[i][j].setIcon(p2);
imageFlag=1;
prevIp1=i;
prevJp1=j;
       }
        else
{
path=game[prevIp1][prevJp1];
str=Integer.toString(path);
  Thread.sleep(200);
icon[prevIp1][prevJp1]=new ImageIcon("images/"+str+".jpg");
Thread.sleep(200);
       b[prevIp1][prevJp1].setIcon(icon[prevIp1][prevJp1]);
b[i][j].setIcon(p1);
prevIp1=i;
prevJp1=j;
       }
           

              /*****************checks for staires**********************/

if(n==10)
{
n=28;
computerimageTraval(n);
p2value=n;
}
else if(n==17)
{
n=37;
computerimageTraval(n);
p2value=n;
}
else if(n==31)
{
n=70;
computerimageTraval(n);
p2value=n;
}
else if(n==45)
{
n=84;
computerimageTraval(n);
p2value=n;
}
else if(n==78)
{
n=97;
computerimageTraval(n);
p2value=n;
}


/*****************Checks for Snakes***************************/
if(n==95)
{
        n=73;
computerimageTraval(n);
p2value=n;
}
else if(n==79)
{
        n=59;
computerimageTraval(n);
p2value=n;
}
else if(n==68)
{
        n=48;
computerimageTraval(n);
p2value=n;
}
else if(n==44)
{
        n=21;
computerimageTraval(n);
p2value=n;
}
else if(n==34)
{
        n=16;
computerimageTraval(n);
p2value=n;
}

}


if(n>=100)
{   
//System.out.println("Congr u r win");
gameover=1;
winerdraw();
}



}
catch(Exception e)
{

}


}

void imageChange(ActionEvent e)
{
int i=j=0;
int flag=0;

try{
 for( i=0;i<10;i++)
    {
for( j=0;j<10;j++)
{
if(e.getSource()==b[i][j])
{
//System.out.println("Button Found");
//System.out.println("b["+i+"]["+j+"]");
flag=1;
break;
}
//System.out.println(j);
}

if(flag==1)
break;
     }


if(imageFlag==0)

Thread.sleep(200);
b[i][j].setIcon(p1);
imageFlag=1;
prevIp1=i;
prevJp1=j;
}
    else
{
path=game[prevIp1][prevJp1];
str=Integer.toString(path);
Thread.sleep(200);
icon[prevIp1][prevJp1]=new ImageIcon("images/"+str+".jpg");
Thread.sleep(200);
       b[prevIp1][prevJp1].setIcon(icon[prevIp1][prevJp1]);
b[i][j].setIcon(p1);
prevIp1=i;
prevJp1=j; 
      }
    }
catch(Exception ee)
{
ee.printStackTrace();
}
}


/******************************Methods of MouseListener****************************/

public void mouseClicked(MouseEvent ae) 
{
 openURL("http://gauravsiwach.blogspot.com");
  
  System.out.println("Clicked");

}
public void mouseEntered(MouseEvent ae)
{
}
public void mouseExited(MouseEvent ae)
{
}
public void mousePressed(MouseEvent ae)
{
}
public void mouseReleased(MouseEvent ae)
{
}


/*******************************BrowserController*********************************/
public static void openURL(String url) 
{
                String osName = System.getProperty("os.name");
                try {
                        if (osName.startsWith("Windows"))
                                Runtime.getRuntime().exec(
                                                "rundll32 url.dll,FileProtocolHandler " + url);
                        else {
                                String[] browsers = { "firefox", "opera"};
                                String browser = null;
                                for (int count = 0; count < browsers.length && browser == null; count++)
                                        if (Runtime.getRuntime().exec(
                                                        new String[] { "which", browsers[count] })
                                                        .waitFor() == 0)
                                                browser = browsers[count];
                                Runtime.getRuntime().exec(new String[] { browser, url });
                        }
                } catch (Exception e) {
                        JOptionPane.showMessageDialog(null, "Error in opening browser"
                                        + ":\n" + e.getLocalizedMessage());
                }
      
    }



public static void main(String args[])
{
 Main m= new Main();
}
}

Game running 




you can download Source code
Snake And Ladders code 


program that read a text file and calculate the frequency of the word and display them in sorted order according their frequency.


import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class FileFrequence implements ActionListener
{
StringTokenizer st,st1;
FileInputStream fr,fr1;
DataInputStream din,din1;
String str,item;
int count;
String word[];
int wordf[];
int num;
String uniqueValues[];
int uniqueFrequence[];
JFrame frame;
JButton b1,b2;
JTextField tf;
JPanel p1,p2,p3,p4,p5,p6;
JFileChooser fileopen;
File file;
String path;
JTextArea jTextArea;
JScrollPane jScrollPane ;


FileFrequence()
{
try{
frame= new JFrame("Text File Word Frequency Calculation");
b1= new JButton("Browes");
b2= new JButton("Calculate");

b1.addActionListener(this);
b2.addActionListener(this);

jTextArea= new JTextArea(" ",20,40);
jScrollPane=new JScrollPane(jTextArea);

fileopen= new JFileChooser();
 
  tf=new JTextField();
p1=new JPanel();
p2=new JPanel();
p3=new JPanel();
p4=new JPanel();
p5=new JPanel();
p6=new JPanel();

  p1.setLayout(new GridLayout(2,1));
p2.setLayout(new FlowLayout());
p3.setLayout(new BorderLayout());
p4.setLayout(new BorderLayout());
p5.setLayout(new GridLayout(2,8));
     
p2.add(b2);
p2.add(b1);
p3.add(p2,BorderLayout.CENTER);
p6.add(jScrollPane);

p1.add(tf);
p1.add(p3);

frame.add(p1,BorderLayout.NORTH);
frame.add(p6,BorderLayout.CENTER);

frame.setVisible(true);
frame.setBounds(100,100,500,500);
}
catch(Exception er)
{}

}

public void actionPerformed(ActionEvent ee)
{
   if(ee.getSource()==b1)
{
fileopen.showDialog(null,"Open File");
path=fileopen.getSelectedFile().getPath();
tf.setText(path);

}
    else if(ee.getSource()==b2)
{
file= new File(path);
if(file.isFile())
find();
}
     }

void find()
{
int n= wordCount();

word= new String[n];
wordf= new int[n];

try{

fr= new FileInputStream(path);
         din = new DataInputStream(fr);

while(true)
        {
            str=din.readLine();

    if(str==null)
break;

st= new StringTokenizer(str," ");

while(st.hasMoreTokens())
  {
item=st.nextToken();

tokenTravel(item,count);
                 count++;

}

}


num = getNumUniqueValues();
uniqueValues = new String[num];
uniqueFrequence= new int[num];


for(int j=0,k=0;j<word.length;j++)
{
if(!containsValue(uniqueValues, word[j]))
{
                      uniqueValues[k] = word[j];
uniqueFrequence[k]=wordf[j];
k++;
}

}
sortString();
int maxf= maxFrequence();
int frecounter=1;
int start=0;

System.out.println("Maximum FRequencu is "+maxf);

          for(int i=0;i<uniqueFrequence.length;i++)
{
if(uniqueFrequence[i]==frecounter)
{
i= i+1;
}
         else
{
wordSorting(start,i);
start=i;
frecounter++;
}
}

for(int i=0;i<num;i++)
{
  System.out.println(uniqueValues[i]+"--"+uniqueFrequence[i]);
  jTextArea.setText(jTextArea.getText()+"\n"+uniqueValues[i]+"--:"+Integer.toString(uniqueFrequence[i]));
}

 }
 catch(Exception ee)
{}

}


void wordSorting(int str,int end)
{

 String temp="";
   int t=0;

           end=end-1;
for (int i=str;i<=end;i++)
{
for (int j=i+1;j<=end;j++)
{
if (uniqueValues[i].compareTo(uniqueValues[j])>0 )
{
       temp=uniqueValues[i];
uniqueValues[i]=uniqueValues[j];                
               uniqueValues[j]=temp;

        t= uniqueFrequence[i];
uniqueFrequence[i]= uniqueFrequence[j];
uniqueFrequence[j]=t;
}
}
}

}

        int getNumUniqueValues()
{
        String[] values = new String[word.length];
        int count = 0;

        for(int j = 0; j < word.length; j++)
{
            if(!containsValue(values, word[j]))
                values[count++] = word[j];
        }
        return count;
        }

boolean containsValue(String[] array, String target)
{
      for(int j = 0; j < array.length; j++)
{
           if(array[j] != null && array[j].equals(target))
              return true;
        }
       return false;
}

void tokenTravel(String item,int n)
{
 int count=0;

try{
FileInputStream fr1= new FileInputStream(path);
DataInputStream din1 = new DataInputStream(fr1);
String str1="",item1="";
StringTokenizer st1;

while(true)
{
str1=din1.readLine();
   
               if(str1==null)
break;

st1=new StringTokenizer(str1," ");

while(st1.hasMoreTokens())
{
  item1=st1.nextToken();
if(item.equals(item1))
{
count=count+1;
word[n]=item1;
wordf[n]=count;
}

}

}
   }
catch(Exception e)
{
}

}

int wordCount()
{
StringTokenizer st;
int wordc=0;
try
  {
FileInputStream fr= new FileInputStream("File.txt");
       DataInputStream din = new DataInputStream(fr);
       String s="";

       while(true)
       {
           s=din.readLine();

if(s==null)
break;
     
st= new StringTokenizer(s," ");

while(st.hasMoreTokens())
  {
  st.nextToken();
wordc++;
  }

}

  }
 catch(Exception e)
{}

  return wordc;
}

void sortString()
{
 int n= uniqueFrequence.length;
 int t=0;
 String str="";

try{
for ( int i = 0 ; i <= n-2 ; i++ )
{
for ( int j = i + 1 ; j <= n-1 ; j++ )
{
if (uniqueFrequence[i] > uniqueFrequence[j] )
{
t = uniqueFrequence[i] ;
uniqueFrequence[i] = uniqueFrequence[j] ;
uniqueFrequence[j] = t;

str=uniqueValues[i];
uniqueValues[i]=uniqueValues[j];
uniqueValues[j]=str;
}
}
}
                             

for(int i=0;i<n;i++)
{
  System.out.println(uniqueFrequence[i]+"--"+uniqueValues[i]);
}
      }
catch(Exception e)
{
System.out.println(e);
}

 }

int maxFrequence()
{
 int max=0;

for(int i=0;i<uniqueFrequence.length;i++)
{
 if(uniqueFrequence[i]>=max)
{
max=uniqueFrequence[i];
}
}
return max;

}

public static void main(String ...a)
{
FileFrequence f= new FileFrequence();

}
}

/*******************************program pic on running mod************************/

/**************************pic of file that is read by program*********************/



/**************************Download Zip file of Above Program*********************
Download Zip File of Above Program