In: Computer Science
Java programming
One of the most popular games of chance is a dice game known as “craps,” which is played in casinos and back alleys throughout the world.
The rules of the game are straightforward:
A player rolls two dice. Each die has six faces. These faces contain 1, 2,3,4,5, and 6 spots. After the dice have come to rest, the sum of the spots on the two upward faces is calculated. If the sum is 7 or 11 on the first throw, the player wins. If the sum is 2, 3, or 12 on the first throw (called “craps”), the player loses (i.e., the “house” wins). If the sum is 4, 5,6,8,9, or 10 on the first throw, then that sum becomes the player’s “points.” To win, you must continue rolling the dice until you “make your points.” The player loses by rolling a 7 before making the points.
Here is the Java Code which simulates "craps" game.Each program run simulates one game.
Sample outputs have been added in the end.
Code:
public class Craps {
public static int rollDie(){ /*This function simulates throwing one die*/
return 1+(int)(Math.random()*6); /*returns a random number between 1 and 6*/
}
public static int sumOnDie(){ /*This function throws two die, finds the sum of the rolls and returns it*/
return rollDie()+rollDie(); /*returns sum of the values on two die*/
}
public static void main(String[] args){
int points,currentRoll; /*points is used to store first roll and currentRoll is used to store any subsequent rolls*/
System.out.println("Starting game :");
points=sumOnDie(); /*finds first roll and assigns it to 'points'*/
System.out.println("You rolled "+points);
if(points==7 || points==11){ /*checks if points is equal to 7 or 11*/
System.out.println("You win!");
}
else if(points==2 || points==3 || points==12){ /*checks if points is equal to 2,3 or 12*/
System.out.println("You lose!");
}
else{ /*if any other number is rolled(4,5,6,8,9,10)*/
do{
currentRoll=sumOnDie(); /*finds the current roll*/
System.out.println("You rolled "+currentRoll);
if(currentRoll==points){ /*checks if current roll is equal to the player's points*/
System.out.println("You win!");
break; /*exits while loop*/
}
else if(currentRoll==7){ /*checks if current roll is equal to 7*/
System.out.println("You lose!");
break; /*exits the loop*/
}
}while(true); /*runs the loop until player wins or loses*/
}
}
}
Sample output-1:
Sample output-2: