HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Playing "craps" for the win

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
playingwincrapsthefor

Problem

No specific question here. I am beginning with Java and here is an exercise. The rules of game:


You roll two dice. Each die has six faces, which contain one, two,
three, four, five and six spots, respectively. 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, you win. If the
sum is 2, 3 or 12 on the first throw (called “craps”), you lose (i.e.,
the “house” wins). If the sum is 4, 5, 6, 8, 9 or 10 on the first
throw, that sum becomes your “point.” To win, you must continue
rolling the dice until you “make your point” (i.e., roll that same
point value). You lose by rolling a 7 before making your point.

```
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;

public class helloworld {
private static int point;
private static enum possibleResults {UNDEFINED, WIN, LOSE};
private static possibleResults gameResult = possibleResults.UNDEFINED;
private static String causeOfLose;
private static String causeOfWin;

public static int rollDice(int n) {
int sum = 0;
Random randomNumbers = new Random();
for(int i=0; i<n; i++) {
sum += (1 + randomNumbers.nextInt(6));
}
System.out.printf("Rolling dice... You got %d\n", sum);
return sum;
}

public static void firstRoll() throws IOException {
waitUser();
int tmp = rollDice(2);
if(tmp == 7 || tmp == 11) {
gameResult = possibleResults.WIN;
causeOfWin = String.format("you have got a lucky number in the first round: %d.", tmp);
} else if(tmp == 2 || tmp == 3 || tmp == 12) {
gameResult = possibleResults.LOSE;
causeOfLose = String.format("you have got an unlucky number in the first round: %d.", tmp);
} else {
point = tmp;
System.out.printf("Your point is %d, you need to make your point to win.%n", point);

Solution

-
A code currently in main should be wrapped in its own method (game perhaps).

-
Business logic shall be performed as high in the call tree as possible. Regarding your code this principle means that neither firstRoll nor moreRolls should call declareResults. The same (questionably) applies to the while loop in moreRolls.

Consider a game skeleton along the lines of

result = firstRoll();
while (result == UNDEFINED)
    result = moreRoll();
declareResults();


-
moreRolls creates a Scanner and never uses it.

-
causeOfWin and causeOfLose are mutually dependent. You don't need two distinct variables: cause would be enough.

Code Snippets

result = firstRoll();
while (result == UNDEFINED)
    result = moreRoll();
declareResults();

Context

StackExchange Code Review Q#68870, answer score: 12

Revisions (0)

No revisions yet.