Print Friendly and PDF
java players game , mini game project in java

Program:

import java.util.*;
class Game
{
public static boolean gameison=true;
public static int currentplayer=1;
public static void nextPlayer()
{
currentplayer++;
if(currentplayer>4)
 currentplayer=1;
}

public static void main(String[] a)
{
Dice d=new Dice();
Player p1= new Player(d,1);
Player p2= new Player(d,2);
Player p3= new Player(d,3);
Player p4= new Player(d,4);
System.out.println("Lets start the game.....");
p1.start();
p2.start();
p3.start();
p4.start();
try
{
p1.join();
p2.join();
p3.join();
p4.join();
}catch(Exception e)
{}

}
}
class Dice
{
int score;
Random r;
Player p;
public Dice()
{
r=new Random();
}
public int turn(int playerno)
{
if(playerno==Game.currentplayer)
{
p=new Player();
score=r.nextInt(6);
System.out.println("Player no "+playerno+" gets "+score+" in his turn and his score is "+(p.score+score)+" now");
Game.nextPlayer();
}
else
{
 try{wait();}catch(Exception e){}
}
return score;
}
}

class Player extends Thread
{
Dice dice;
int score=0, pno;

public Player()
{}

public Player(Dice d,int playerno)
{
dice=d;
pno=playerno;
}

public void run()
{
while(Game.gameison)
 {
 synchronized(dice)
  {
  score=score+dice.turn(pno);
  //System.out.println("Score of "+pno+" player is "+score+" now");
  if(score>=25)
   {
  System.out.println(pno+"is the winner");
  Game.gameison=false;
  }
  try{wait();}
  catch(Exception e){}
  }
 }
}
}
zubairsaif

Zubair saif

A passionate writer who loves to write on new technology and programming

Post A Comment:

0 comments: