C#骰子模拟程序开发求助:实现掷骰及指定运算功能
Hey there! I get that starting out with C# can feel a bit overwhelming, so let's walk through building this dice roller step by step. We'll use Windows Forms since it's a common choice for beginner assignments, but the core logic translates to other frameworks too.
Step 1: UI Setup
First, drag these controls onto your form and configure them:
- A NumericUpDown (name:
numDiceCount): SetMinimumto 1,Maximumto 6, defaultValueto 1. This lets users pick 1-6 dice. - A ComboBox (name:
cboDiceSides): Add these values to itsItemslist: 4, 6, 8, 10, 12, 14, 16, 18, 20. SetDropDownStyletoDropDownListso users can't type invalid values. - A Button (name:
btnRollDice): Set text to "Roll Dice". - Two RadioButtons:
- Name:
rbtnMultiply, text: "Multiply first two dice" - Name:
rbtnTenPlus, text: "First die ×10 + Second die"
- Name:
- A Label (name:
lblCalculationResult): Leave empty initially, it'll show operation results. - A ListBox (name:
lstRollHistory): This keeps all past roll results visible.
Step 2: Core Dice Rolling Logic
First, declare a class-level Random instance (this avoids repeated numbers if you roll quickly):
private Random _random = new Random();
Next, add the click event handler for the "Roll Dice" button. This handles rolling, storing results, and calculations:
private void btnRollDice_Click(object sender, EventArgs e) { // Get user selections from UI int diceCount = (int)numDiceCount.Value; int diceSides = int.Parse(cboDiceSides.SelectedItem.ToString()); // Roll each die and collect results List<int> rollResults = new List<int>(); for (int i = 0; i < diceCount; i++) { // Generate a number between 1 and the selected number of sides (inclusive) int roll = _random.Next(1, diceSides + 1); rollResults.Add(roll); } // Format the roll for display and add to history string rollDisplayText = $"Roll ({diceCount}d{diceSides}): {string.Join(", ", rollResults)}"; lstRollHistory.Items.Add(rollDisplayText); // Calculate result for first two dice (if applicable) if (diceCount >= 2) { int firstDie = rollResults[0]; int secondDie = rollResults[1]; int calculation = 0; if (rbtnMultiply.Checked) { calculation = firstDie * secondDie; lblCalculationResult.Text = $"Multiplication: {firstDie} × {secondDie} = {calculation}"; } else if (rbtnTenPlus.Checked) { calculation = (firstDie * 10) + secondDie; lblCalculationResult.Text = $"10×First + Second: ({firstDie}×10) + {secondDie} = {calculation}"; } } else { // Clear calculation label if fewer than 2 dice are rolled lblCalculationResult.Text = ""; } }
Step 3: Optional Polish (For Extra Points)
- Add a "Clear History" button with this handler to let users reset the roll list:
private void btnClearHistory_Click(object sender, EventArgs e) { lstRollHistory.Items.Clear(); lblCalculationResult.Text = ""; } - Resize controls and adjust fonts to make the form look cleaner—small styling touches make assignments stand out.
Quick Explanation of Key Bits
- The class-level
Randominstance ensures we get unique, random rolls every time (creating a newRandomon each click can cause duplicate results because it uses the system clock as a seed). - The
rollResultslist stores each die's value, which we format into a readable string to add to the history list box. - The calculation logic checks if we have at least two dice, then uses the selected radio button to compute and display the result.
That's all you need to meet your assignment requirements! Feel free to tweak things if you want to adapt it to a different framework (like WPF) or add extra features.
内容的提问来源于stack exchange,提问作者Oliver Toth

