我正在设计一个允许用户选择骰子的Windows程序,然后在滚动时显示可能的结果。
此时,无论选择何种骰子,我都只能从50中得到可能的结果。我认为这与公共RollDice()中的问题有关,但不能确定。 我正在使用两个名为FormDice.cs和RollDice.cs
的类这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace
{
public partial class FormDice : Form
{
public FormDice()
{
InitializeComponent();
sixRadioButton.Checked = true;
}
//declare variables
int sides;
int answer;
//assign clear button
private void clearButton_Click(object sender, EventArgs e)
{
twoRadioButton.Checked = false;
sixRadioButton.Checked = true;
tenRadioButton.Checked = false;
fiftyRadioButton.Checked = false;
}
//assign event to roll button
private void rollButton_Click(object sender, EventArgs e)
{
//if statements check which number checked
if (twoRadioButton.Checked)
{
sides = 2;
RollDice rolldice = new RollDice();
answer = rolldice.Roll();
}
else if (sixRadioButton.Checked)
{
sides = 6;
RollDice rolldice = new RollDice();
answer = rolldice.Roll();
}
else if (tenRadioButton.Checked)
{
sides = 10;
RollDice rolldice = new RollDice();
answer = rolldice.Roll();
}
else if (fiftyRadioButton.Checked)
{
sides = 50;
RollDice rolldice = new RollDice();
answer = rolldice.Roll();
}
else
{
RollDice rolldice = new RollDice();
answer = rolldice.Roll();
}
resultsListBox.Items.Add(answer.ToString());
}
//exit program
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
//about message box
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Dice Magic Version 1.0\nProgrammer: PaulPresutto", `enter code here`"Dice Magic", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void twoRadioButton_CheckedChanged(object sender, EventArgs e)
{
}
我的RollDice.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace
{
class RollDice
{
//variables
private numberOfSides;
private Random randomNumberGenerator = new Random();
public RollDice()
{
numberOfSides = 6;
numberOfSides = 2;
numberOfSides = 10;
numberOfSides = 50;
}
//constructor
public RollDice(int sides)
{
numberOfSides = sides;
}
public int Roll()
{
return randomNumberGenerator.Next(1, numberOfSides + 1);
}
}
}
private void resultsListBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
答案 0 :(得分:4)
在第一个代码段中更改所有这些内容:
sides = 10;
RollDice rolldice = new RollDice();
致电您的超负荷ctor接受" side"值:
sides = 10;
RollDice rolldice = new RollDice(sides);
由于默认ctor多次覆盖同一个变量,因此numberOfSides
的值始终为50.
public RollDice()
{
numberOfSides = 6;
numberOfSides = 2;
numberOfSides = 10;
numberOfSides = 50; // last value wins out - you'll want to fix this
}
答案 1 :(得分:3)
您在RollDice
构造函数中将边数设置为6,然后是2,然后是10,再是50。所以它总是最终为50。
你已经有了一个构造函数,可以传递多边数。尝试使用它。例如:
else if (fiftyRadioButton.Checked)
{
RollDice rolldice = new RollDice(50);
}