以窗体形式简单滚动骰子应用程序(猪游戏)。
点击"滚动骰子"按钮,如果我掷骰子1,则玩家的总数将恢复为0
而且我也想删除我的数组我知道这是没有意义的,但是在删除数组后会出现很多错误。
我如何实现这一目标?
public partial class PigForm : Form {
Image[] diceImages;
int[] dice = new int[1] { 0 };
Random roll = new Random();
public PigForm() {
InitializeComponent();
}
private void cancelGameBotton_Click(object sender, EventArgs e) {
this.DialogResult = DialogResult.OK; // This hides the form, and causes ShowDialog() to return in WhichGame form
}
private void rollDieBotton_Click(object sender, EventArgs e) {
RollDice();
Pig.Hold();
}
private void playAnotherGameLabel_Click(object sender, EventArgs e) {
}
private void RollDice() {
for (int i = 0; i < dice.Length; i++){
var currentRoll = roll.Next(1, 7);
dice[i] += currentRoll;
dicePictureBox.Image = diceImages[currentRoll-1];
playersTotal.Text = String.Format("{0}", dice[i]);
}//end for
} // end RollDice
private void PigForm_Load(object sender, EventArgs e) {
diceImages = new Image[6];
diceImages[0] = Properties.Resources.Alea_1;
diceImages[1] = Properties.Resources.Alea_2;
diceImages[2] = Properties.Resources.Alea_3;
diceImages[3] = Properties.Resources.Alea_4;
diceImages[4] = Properties.Resources.Alea_5;
diceImages[5] = Properties.Resources.Alea_6;
}
} //end class
} //end namespace
答案 0 :(得分:1)
删除数组时会发生错误,因为您可能只是删除括号和声明中的值,但是您没有修改使用数组的代码。
根据我的理解,我删除了您的阵列,并使您的标签“恢复”。如果骰子滚动1,则显示消息框为0。 如果存在一些误解,请不要发表评论。
Image[] diceImages;
int dice = 0; // array removed because it is not needed
Random roll = new Random();
private void rollDieBotton_Click(object sender, EventArgs e) {
RollDice();
Pig.Hold();
if (dice == 1)
{
playAnotherGameLabel.Text = "0";
MessageBox.Show("Sorry you have thrown a 1. your turn is over!");
}
}
private void RollDice() {
// for loop is not needed because it is no longer an array
var currentRoll = roll.Next(1, 7);
dice[i] += currentRoll; // this in my opinion should be = not += because the result of the next roll will be absurd
dicePictureBox.Image = diceImages[currentRoll-1];
playersTotal.Text = String.Format("{0}", dice[i]);
} // end RollDice
答案 1 :(得分:0)
我不确定我完全理解你的问题,但这是一个建议:
private void RollDice()
{
bool gameComplete = false;
for (int i = 0; i < dice.Length; i++)
{
var currentRoll = roll.Next(1, 7);
if (currentRoll == 1)
{
dice = new int[1] { 0 };
gameComplete = true;
}
else
{
dice[i] += currentRoll;
dicePictureBox.Image = diceImages[currentRoll - 1];
}
playersTotal.Text = String.Format("{0}", dice[i]);
}//end for
if (gameComplete)
{
MessageBox.Show("Sorry you have thrown a 1. your turn is over!");
}