Write a sample pressyourluck dice game The game works as fol
Solution
Human VS Human Game Code:
===============================================
import java.util.*;
public class PressYourLuck{
public static int rollDie()
{
Random ran = new Random();
int x = ran.nextInt(6)+1;
return x;
}
public static int newScore(int oldScore,int rollValue)
{
if ((rollValue==7)||(rollValue==2)||(rollValue==12)){
return -1;
}
else{
return (oldScore+rollValue);
}
}
public static int whoGoesFirst()
{
Random ran = new Random();
int x = ran.nextInt(2)+1;
return x;
}
public static String winner(int playerNumber)
{
return (\"Player \"+playerNumber+\" wins the game\");
}
public static char keepRolling()
{
System.out.print(\"Do you want to continue to Roll (y or n) : \");
Scanner scan = new Scanner(System.in);
char s = scan.next().trim().charAt(0);
if((s==\'y\')||(s==\'n\')){
return s;
}
else{
System.out.print(\"Please enter correct option\");
return keepRolling();
}
}
public static int gamePlay(int oldScore,int playerNumber)
{
int firstDiceScore = rollDie();
int secondDiceScore = rollDie();
int totalDiceScore = firstDiceScore + secondDiceScore;
System.out.println(\"Player \"+playerNumber+\" current Dice score:\"+totalDiceScore);
int updatedScore = newScore(oldScore,totalDiceScore);
if (updatedScore==-1){
System.out.println(\"Player \"+playerNumber+\" just lost\");
return (oldScore+totalDiceScore);
}
else{
char c = keepRolling();
if (c==\'y\'){
return gamePlay(updatedScore,playerNumber);
}
else{
return updatedScore;
}
}
}
public static void main(String []args)
{
int firstPlayer = whoGoesFirst();
int secondPlayer;
if (firstPlayer==1){
secondPlayer = 2;
}
else{
secondPlayer = 1;
}
System.out.println(\"Player \"+firstPlayer+\" starts game\");
int firstPlayerScore = gamePlay(0,firstPlayer);
System.out.println(\"Player \"+firstPlayer+\" total Score \"+firstPlayerScore);
System.out.println(\"Player \"+secondPlayer+\" starts game\");
int secondPlayerScore = gamePlay(0,secondPlayer);
System.out.println(\"Player \"+secondPlayer+\" total Score \"+secondPlayerScore);
if(firstPlayerScore>secondPlayerScore){
System.out.println(winner(firstPlayer));
}
else if (firstPlayerScore<secondPlayerScore){
System.out.println(winner(secondPlayer));
}
else {
System.out.println(\"Game Draw\");
}
}
}
=========================================================

