You are on page 1of 6

import javax.swing.

*;
import java.util.Arrays;
import java.util.Random;

public class DicePoker1 {

//Create a static array for the scores


static Score[] scoresArray = new Score[0];

public static void main(String[] args) {


start();
}

//Initialize the game


public static void start() {

int playAgain = 0;
//Loop while confirmation is 0
while (playAgain == 0) {
//Simulate the game
simulate();
//Prompt the user to play again,
//if yes, the value returned is 0 otherwise 1 ending the loop
playAgain = JOptionPane.showConfirmDialog(
null,
"Play Again?",
"Confirm to Play Again.",
JOptionPane.YES_NO_OPTION);
}
}

//Simulate the dice poker game


public static void simulate() {

//Get the player name


String playerName = getPlayerName();

//Initialize the starting bank amount and attempt


int currentMoney = 6;
int attempts = 5;

//Declare a string to hold the game result output


String gameResult = "Game Result \n";

//Loop until the attempt reaches 0 or the bank amount money is equal or
less than zero
for (int round = 1; round <= 5; round++) {

//Get the user bet


int bet = getUserBet(currentMoney, attempts);
//Call the dice roll twice and assign to 2
int dice1 = rollDice();
int dice2 = rollDice();

String roundStatus;
int currentWinnings;

//Check if dices are sequential


if ((dice1 - dice2 == 1) || (dice1 - dice2 == -1)) {
roundStatus = "win";
currentWinnings = bet * 2;
}
//Check if dices are identical
else if (dice1 == dice2) {
roundStatus = "win";
currentWinnings = bet * 3;
}
//If neither sequential or identical, return 0;
else {
roundStatus = "lose";
currentWinnings = bet * -1;
}

String roundResult = "Round " + round + " result: \n" +


"Dice 1: " + dice1 + ", Dice 2: " + dice2 + "\n\n" +
"You " + roundStatus + " £" + currentWinnings;

//Display the current round result


showMessageDialogBox(roundResult, "Round Result");

gameResult = gameResult
+ "Round " + round + ": "
+ "Bet Amount: £" + bet
+ ", Dices: " + dice1 + "-" + dice2
+ ", Amount Won/Lose: £" + currentWinnings
+ "\n";

//Add or deduct the current winning to the current money


currentMoney += currentWinnings;

//Decrement attempt by 1
attempts--;

//If the current money is depleted, end the loop


if (currentMoney <= 0) {
break;
}
}
//Add the final score/remaining money to the game result
gameResult = gameResult
+ "\nFinal Score: £" + currentMoney;

//Display the game result


showMessageDialogBox(gameResult, "Game Result");

//Add, sort and print the scores


addScore(new Score(playerName, currentMoney));
System.out.println(Arrays.toString(scoresArray));
sortScores();
printScores();
}

private static String getPlayerName() {

while (true) {

//Write the guidelines


String guidelines = "Dice Poker Guidelines: \n" +
"\t* Place your bets from £1 up to £4 for each round. \n" +
"\t* Win 2x or 3x your bet depending on the dice result\n" +
"\t* If the dice result are in sequence, win x2 you bet!\n
(e.g. 1 & 2, 5 & 4, etc. but not 6 & 1) \n" +
"\t* or x3 if the dice results are identical!\n" +
"\t* The game will end after 5 rounds or you run out of money
to bet.\n" +
"\t* Increase your money and be included in our high score
list! \n" +
"\n\tMay the force be with you!\n";

//Display the rules ang get the player name


String playerName = JOptionPane.showInputDialog(
guidelines + "\n Please enter your name to start playing.");

//Check if player name is not blank, if true return the player name
if (!playerName.equals("")) {
return playerName;
} else {
showErrorMessageDialogBox(
"Invalid input for name. Try again.",
"Invalid input");
}
}
}

//Get user bet


public static int getUserBet(int money, int attempts) {

int bet = 0;
while (true) {
//Implement try catch to capture bad input from user
try {
//Display attempts remaining and get the bet from the user
String input = JOptionPane.showInputDialog(
"Current Money: £" + money + "\n" +
"Attempts Remaining: " + attempts + "\n" +
" Enter your bet (1 - 4 only)");
//Convert the input to integer
bet = Integer.parseInt(input);
//Determine if bet is between 1 and 4 then proceed,
//otherwise throw exception
if (bet < 1 || bet > 4) {
showErrorMessageDialogBox(
"Invalid bet. Must be £1 - £4 only",
"Invalid input");
} else if (bet > money) {
showErrorMessageDialogBox(
"Invalid bet. Cannot be greater than current money",
"Invalid input");
} else {
return bet;
}
} catch (NumberFormatException e) {
showErrorMessageDialogBox(
"Invalid value for bet. Try again.",
"Invalid input");
}
}
}

//Helper method to display message dialog box


public static void showMessageDialogBox(String message, String title) {
JOptionPane.showMessageDialog(null,
message,
title,
JOptionPane.INFORMATION_MESSAGE);
}

//Helper method to display error message dialog box


public static void showErrorMessageDialogBox(String message, String title) {
JOptionPane.showMessageDialog(null,
message,
title,
JOptionPane.ERROR_MESSAGE);
}

//Returns a random integer from 1 to 6


public static int rollDice() {
return new Random().nextInt(5) + 1;
}

//Adds the score to the scores array


public static void addScore(Score score) {
//Get the size of the scores array
int size = scoresArray.length;

//Resize the scores array by 1


scoresArray = Arrays.copyOf(scoresArray, size + 1);

//Add the score to the scores array last index


scoresArray[size] = score;
}

//Sorts the scores array


public static void sortScores() {
//Get the current size
int size = scoresArray.length;

//We loop each score in the array


for (int index = 0; index < size; index++) {

//Check if the next index is out of bounds


if (index + 1 != size) {
//Loop starting from the next index
for (int next = index + 1; next < size ; next++) {

//Get the current score and the next score


Score current = scoresArray[index];
Score nextScore = scoresArray[next];

//swap if the current point is less than the next score


if (current.getPoints() < nextScore.getPoints()) {
Score tmp = scoresArray[index];
scoresArray[index] = nextScore;
scoresArray[next] = tmp;
}
}
}
}
}

//Prints the score results


public static void printScores() {
//Get the current size
int size = scoresArray.length;

//Compose the high score result


String scoreResult = "High Scores: \n";
//Loop each record in the scores array, then append it to the output
for (int position = 1; position <= size; position++) {

//Get the current score from the value of position - 1 (since index
starts from 0);
Score current = scoresArray[position - 1];
scoreResult = scoreResult + "\t"
+ "No. " + position
+ ": " + current.toString() + "\n";
}

//Display the scores result


showMessageDialogBox(scoreResult, "Scores Result");
}
}

You might also like