Dice Game

import java.util.Random;
import java.util.Scanner;

// Die class representing a single die
class Die {
    private int faceValue;
    private Random rand;

    // Constructor initializes the random object and rolls the die once
    public Die() {
        rand = new Random();
        roll();
    }

    // Method to roll the die and generate a value between 1 and 6
    public void roll() {
        faceValue = rand.nextInt(6) + 1; // Generates number between 1 and 6
    }

    // Getter to retrieve the face value of the die
    public int getFaceValue() {
        return faceValue;
    }

    @Override
    public String toString() {
        return String.valueOf(faceValue);
    }
}

// DiceGame class containing the interactive game logic
public class DiceGame {
    public static void main(String[] args) {
        try (Scanner scan = new Scanner(System.in)) {
            Die die1 = new Die(); // First die
            Die die2 = new Die(); // Second die
            int totalScore = 0; // Player's total score
            String command;

            System.out.println("\nšŸŽ² Welcome to the Interactive Dice Rolling Game! šŸŽ²");
            System.out.println("Commands: R (Roll Dice), E (Exit Game)");

            // Game loop
            while (true) {
                System.out.print("\nEnter a command (R to Roll / E to Exit): ");
                command = scan.nextLine().trim().toUpperCase();

                switch (command) {
                    case "R": // Roll the dice
                        die1.roll();
                        die2.roll();

                        // Calculate the sum of the dice
                        int sum = die1.getFaceValue() + die2.getFaceValue();
                        totalScore += sum;

                        // Display the result
                        System.out.println("You rolled: šŸŽ² " + die1 + " + šŸŽ² " + die2 + " = " + sum);
                        System.out.println("Your current total score: " + totalScore);
                        break;

                    case "E": // Exit the game
                        System.out.println("\nGame Over! šŸŽ‰ Your final score: " + totalScore);
                        System.out.println("Thanks for playing! Goodbye!");
                        return;

                    default:
                        System.out.println("Invalid command! Please enter 'R' to roll or 'E' to exit.");
                }
            }
        }
    }
}
Scroll to Top