Skip to main content

Snakes and ladder game in java

import java.io.*;
class game
{
int pos,p,f;
String pname;
game(String name)
{
pname=name;
pos=0;
f=0;
}

public void play(int val)
 {
if(val==0)
val=1;

pos=pos+val;
System.out.println(pname+"\t is at \t"+ pos + " position");

f=0;
switch (pos)
  {
case 4:  pos+=10;  f=4; break;
case 9:  pos+=22; f=22; break;
case 17: pos-=17; f=-17; break;
case 19: pos+=19; f=19; break;
case 21: pos+=21; f=21; break;
case 28: pos+=56; f=56; break;
case 51: pos+=16; f=16; break;
case 54: pos-=20; f=-20; break;
case 62: pos-=43; f=-43; break;
case 64: pos-=4;  f=-4; break;
case 71: pos+=20; f=20; break;
case 80: pos+=20; f=20; break;
case 87: pos-=63; f=-63; break;
case 93: pos-=20; f=-20; break;
case 95: pos-=20; f=-20; break;
case 98: pos-=19; f=-19; break;
}
if(f>0)
System.out.println(pname+"\t has climbed a ladder and reached to\t"+ pos + " with "+f+ " points increment");
else if (f<0)
System.out.println(pname+"\t gotten bitten by a snake and fell to\t"+ pos + " with "+f+ " points decrement");
}
}


class Snakes
{
public static void main(String args[])throws Exception
{
DataInputStream d = new DataInputStream(System.in);
String a,b;
int w=-1;
long val=0;
System.out.println("Enter name of players");
a= d.readLine();
b= d.readLine();
game obj1=new game(a);
game obj2=new game(b);

while(obj1.pos<100||obj2.pos<100)
{
System.out.println("Enter any number");
val=Long.parseLong(d.readLine());

obj1.play((int)(6*Math.random())%6);

if(obj1.pos==100 )
{
 w=1;
   break;
}

System.out.println("Enter any number");
val=Long.parseLong(d.readLine());
obj2.play((int)(6*Math.random())%6);


 if(obj2.pos==100 )
  {
 w=2;
   break;
  }


}

if(w==1)
System.out.println(obj1.pname+" wins");
else
System.out.println(obj2.pname+" wins");
}

}

Comments

Popular posts from this blog

unix commands