You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java开发D&D角色属性掷骰器技术问询:多类架构与功能实现

Building Your D&D Stat Roller: Step-by-Step Guide

Hey there! I see you're a Java newbie working on a D&D stat roller—cool project! Let's walk through expanding your existing code into that 3-class architecture you need, while hitting all your requirements.

First, let's restate your requirements clearly to keep us aligned:

  • Let the user input a number X, then roll X sets of X D6 dice
  • Let the user choose whether to reroll any 1s on the D6
  • For each set, keep only the 3 highest values
  • Output each set's result (we’ll match your example of showing sums of the top 3, but we’ll also include how to print individual values if needed)

First: The 3-Class Architecture Breakdown

We’ll split this into three focused classes, each with a single responsibility to keep the code clean and maintainable:

  1. Die: Handles individual die rolls, including reroll logic for 1s
  2. StatRoller: Manages rolling a single set of X D6s, sorting to pick the top 3, and calculating their sum
  3. DnDStatApp: Handles user input, orchestrates the rolling process, and outputs the final results

1. Refactoring the Die Class

Your existing RollDie is a great start—we’ll turn it into a reusable Die class with built-in reroll functionality. This class only handles low-level die rolling logic.

public class Die {
    private static final int SIDES = 6;

    // Rolls a single D6, with optional reroll of 1s
    public int roll(boolean rerollOnOne) {
        int result = (int) (Math.random() * SIDES) + 1;
        // If reroll is enabled and we rolled a 1, roll again (once)
        if (rerollOnOne && result == 1) {
            result = (int) (Math.random() * SIDES) + 1;
            // Want to reroll until you get a non-1? Replace the if with a while loop here!
        }
        return result;
    }
}

2. The StatRoller Class

This class handles the "set" logic: rolling multiple dice, sorting them, picking the top 3, and calculating their sum. It uses the Die class under the hood to keep concerns separated.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class StatRoller {
    private Die die;

    public StatRoller() {
        this.die = new Die();
    }

    // Rolls X D6s, applies reroll rule, returns the top 3 values
    public List<Integer> rollSingleSet(int numDicePerSet, boolean rerollOnOne) {
        List<Integer> rolls = new ArrayList<>();
        // Roll X dice
        for (int i = 0; i < numDicePerSet; i++) {
            rolls.add(die.roll(rerollOnOne));
        }
        // Sort rolls from highest to lowest
        Collections.sort(rolls, Collections.reverseOrder());
        // Keep only the top 3 (handles edge case if X < 3)
        return rolls.subList(0, Math.min(3, rolls.size()));
    }

    // Helper method to get the sum of the top 3 rolls (matches your example output)
    public int getSumOfTop3(List<Integer> top3Rolls) {
        return top3Rolls.stream().mapToInt(Integer::intValue).sum();
    }
}

3. The Main Application Class (DnDStatApp)

This is the entry point of your program—it interacts with the user, collects input, runs all the rolls, and prints the results. We’ll use the Scanner you already planned for!

import java.util.Scanner;
import java.util.List;

public class DnDStatApp {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        StatRoller statRoller = new StatRoller();

        // Get X from the user
        System.out.print("Enter the number of dice per set (and number of sets): ");
        int X = scanner.nextInt();

        // Get reroll preference
        System.out.print("Do you want to reroll 1s? (Y/N): ");
        String rerollChoice = scanner.next().trim().toUpperCase();
        boolean rerollOnOne = rerollChoice.equals("Y");

        // Roll X sets and output results
        System.out.println("\nYour results are:");
        for (int i = 0; i < X; i++) {
            List<Integer> top3 = statRoller.rollSingleSet(X, rerollOnOne);
            // Print sum of top 3 (matches your example)
            int sum = statRoller.getSumOfTop3(top3);
            System.out.print(sum + " ");
            
            // Want to print individual top 3 values instead? Uncomment this line:
            // System.out.print(top3 + " ");
        }

        scanner.close();
    }
}

How It All Works Together

  • The Die class does one job and does it well: rolling a die with optional rerolls. No extra clutter here.
  • The StatRoller handles the group logic—rolling multiple dice, sorting, and picking the top values—without worrying about user input or die mechanics.
  • The DnDStatApp is the "glue" that talks to the user, uses the other classes to generate results, and shows the output.

Quick Adjustments You Might Want

  • If you want to keep rerolling 1s until you get a non-1, replace the if statement in Die.roll() with a while loop.
  • To print individual top 3 values per set instead of sums, just swap the commented/uncommented lines in the main app’s output loop.
  • If you want to enforce X >=3 (since D&D usually uses 4 dice per set), add a quick check after getting X from the user to prompt for a valid number.

内容的提问来源于stack exchange,提问作者Logan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:10:43