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

C#骰子模拟程序开发求助:实现掷骰及指定运算功能

C# Dice Roller Solution for Your Assignment

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): Set Minimum to 1, Maximum to 6, default Value to 1. This lets users pick 1-6 dice.
  • A ComboBox (name: cboDiceSides): Add these values to its Items list: 4, 6, 8, 10, 12, 14, 16, 18, 20. Set DropDownStyle to DropDownList so 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"
  • 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 Random instance ensures we get unique, random rolls every time (creating a new Random on each click can cause duplicate results because it uses the system clock as a seed).
  • The rollResults list 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 17:58:01