2016-03-08 97 views
-4

我試圖讓我的開始按鈕在圖片頂部標記的所有4個框中生成一個顏色。顏色不應該是一樣的。它應該像樂透一樣工作,但用顏色代替數字。任何人都可以告訴我我的代碼有什麼問題嗎?如何製作隨機按鈕背景顏色生成器?

Picture

而這就是我的代碼;

 } 

     private void buttonStart_Click(object sender, EventArgs e) 
     { 
      buttontest.BackColor = GetRandomColor(); 
      timer1.Enabled = true; 
     } 

     private void timer1_Tick(object sender, EventArgs e) 
     { 
      Color RandomColor = GetRandomColor(); 
      buttontest.BackColor = GetRandomColor(); 
      buttontest.Refresh(); 
     } 

     private Random random; 

     private void MainForm_Load(object sender, EventArgs e) 
     { 
      //Create a new instance of the random class 
      random = new Random(); 
     } 

     private Color GetRandomColor() 
     { 
      return Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255)); 
     } 

     private void buttontest_Click(object sender, EventArgs e) 
     { 
      timer1.Enabled = true; 
      buttontest.BackColor = Color.Red; 

     } 


    } 
} 
+1

我沒有看到你在任何地方設置按鈕的背景。 –

+0

'Color RandomColor = GetRandomColor();' - >'yourButton.BackColor = GetRandomColor(); yourButton.Refresh();' – TaW

+0

是那裏的計時器,因爲你希望它每次計時器都會改變? –

回答

0

回答你的問題是類似的東西:

Random random = new Random(); 

private Color GetRandomColor() 
{ 
    return Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255)); 
} 

private void btnStart_Click(object sender, EventArgs e) 
{ 
    button1.BackColor = GetRandomColor(); 
    button2.BackColor = GetRandomColor(); 
    button3.BackColor = GetRandomColor(); 
    button4.BackColor = GetRandomColor(); 
} 

但是我知道這場比賽主謀你想擁有一組特定的顏色。那麼代碼應該是類似的東西:

List<Color> possibleColors = new List<Color>() 
{ 
    Color.Red, 
    Color.Green, 
    Color.Gold, 
    Color.Blue 
}; 

private Color GetRandomColorOfList() 
{ 
    return possibleColors[random.Next(0, possibleColors.Count)]; 
} 

private void button5_Click(object sender, EventArgs e) 
{ 
    button1.BackColor = GetRandomColorOfList(); 
    button2.BackColor = GetRandomColorOfList(); 
    button3.BackColor = GetRandomColorOfList(); 
    button4.BackColor = GetRandomColorOfList(); 
} 
+0

原來的問題有一個限制:'顏色不應該是相同的'。 –

0

您可以使用上述邁克爾·賽德爾建議列表,將它洗用的就是點擊Start按鈕時,例如,費雪耶茨算法來實現here

private static Random rng = new Random(); 

public static void Shuffle<T>(this IList<T> list) 
{ 
    int n = list.Count; 
    while (n > 1) { 
     n--; 
     int k = rng.Next(n + 1); 
     T value = list[k]; 
     list[k] = list[n]; 
     list[n] = value; 
    } 
} 
List<Color> possibleColors = new List<Color>() 
{ 
    Color.Red, 
    Color.Green, 
    Color.Gold, 
    Color.Blue 
}; 

private void button5_Click(object sender, EventArgs e) 
{ 
    possibleColors.Shuffle(); 
    button1.BackColor = possibleColors[0]; 
    button2.BackColor = possibleColors[1]; 
    button3.BackColor = possibleColors[2]; 
    button4.BackColor = possibleColors[3]; 
}