2015-11-08 175 views
-1

好吧我正在嘗試製作一個GUI骰子游戲,其中的骰子數字在文本框中表示。C#GUI骰子游戲通過引用

我必須創建一個代表骰子的類,至少我的一個方法必須通過引用正確傳遞參數。我的問題是我對課程或傳球參數不太熟悉

我在 rd.RollDice1(ref dice1); rd.RollDice2(ref dice2); (我確定我沒有錯誤地構建RollDice類) 請問有沒有人可以幫助我?

這裏是我到目前爲止的代碼:

public partial class Form1 : Form 
{ 
    private RollDice rd; 


    public Form1() 
    { 
     InitializeComponent(); 
     rd = new RollDice(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     int dice1, dice2; 

     const int EYE = 1; 

     const int BOX = 6; 

     rd.RollDice1(ref dice1); 

     rd.RollDice2(ref dice2); 

     string result = string.Format("{0}", dice1); 
     string result2 = string.Format("(0)", dice2); 

      textBox1.Text = result; 

       textBox2.Text = result; 

     if (dice1 == EYE && dice2 == BOX) 
     { 
      MessageBox.Show("You rolled a Snake Eyes!"); 

     } 
     if (dice1 == BOX && dice2 == BOX) 
     { 

      MessageBox.Show("You rolled BoxCars!"); 

     } 

     else 
     { 
      MessageBox.Show("You rolled a {0} and a {1}", dice1, dice2); 
     } 
    } 
} 

}

class RollDice 
{ 

    const int EYE = 1; 
    const int BOX = 6; 

    public int RollDice1(ref int dieValue1) 
    { 
     Random randomNums = new Random(); 

     dieValue1 = randomNums.Next(1, 7); 

     return dieValue1; 

    } 

    public int RollDice2(ref int dieValue2) 
    { 
     Random randomNums = new Random(); 

     dieValue2 = randomNums.Next(1, 7); 

     return dieValue2; 

    } 






} 

}

+0

'傳遞的參數「我得到一個錯誤的......」' - 和錯誤是什麼?另外,爲什麼你通過引用傳遞*和*返回值?不妨選擇兩種方法中的一種。 – David

+0

啊,這就是爲什麼......我會得到紅色的回報,並繼續努力。謝謝! – eagleye1144

回答

0

傳遞與參考變量需要變量與默認值進行初始化。如果你不具有初始值設定的兩個骰子你的編譯器抱怨"Use of unassigned local variable xxxxx"

private void button1_Click(object sender, EventArgs e) 
{ 

    const int EYE = 1; 
    const int BOX = 6; 

    int dice1 = EYE; 
    int dice2 = BOX; 

    rd.RollDice1(ref dice1); 
    rd.RollDice2(ref dice2); 

    ..... 

但是看着你的代碼有沒有需要通過進行使用參考值,你可以簡單地得到返回值

dice1 = rd.RollDice1(); 
    dice2 = rd.RollDice2(); 
當然

,你應該改變你的類兩種方法,以消除裁判

class RollDice 
{ 
    Random randomNums = new Random(); 

    public int RollDice1() 
    { 
     return randomNums.Next(1, 7); 
    } 

    public int RollDice2() 
    { 
     return randomNums.Next(1, 7); 
    } 
} 
+0

我是怎麼看不到的!?!?哈哈謝謝你,這是完美的! – eagleye1144