我正在構建一個 C# 電影院程式。在 Form1 上,當單擊“保留”按鈕時,我希望 Form 2 上的 21 個按鈕隨機將 6 個座位更改為“紅色”。我希望每次在表格 1 上按下“預訂”按鈕時它都是不同的座位。
這是我正在努力作業的代碼。
Random random = new Random();
private Color GetRandomColor()
{
return Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
}
private void reserve_button_Click(object sender, EventArgs e)
{
button1.BackColor = GetRandomColor();
button2.BackColor = GetRandomColor();
button3.BackColor = GetRandomColor();
button4.BackColor = GetRandomColor();
}


uj5u.com熱心網友回復:
好吧,您應該6 隨機選擇不是的 座位Red并將它們涂成紅色。假設您使用Winforms:
顯示座位的Form2:
using System.Linq;
...
public bool MakeReservation(int count) {
// Buttons to exclude from being painted into red:
HashSet<Button> exclude = new HashSet<Button>() {
//TODO: put the right names here
btnBook,
btnClear,
};
var buttons = Controls // All controls
.OfType<Button>() // Buttons only
.Where(button => button.BackColor != Color.Red) // Non red ones
.Where(button => !exclude.Contains(button)) // we don't want some buttons
.OrderBy(_ => random.NextDouble()) // In random order
.Take(count) // count of them
.ToArray(); // organized as an array
//TODO: you can check here if we have 6 buttons, not less
if (buttons.Length < count) {
// Too few seats are free
return false;
}
// Having buttons selected, we paint them in red:
foreach(var button in buttons)
button.BackColor = Color.Red;
return true;
}
當Form1打開一個新的Form2或找到現有的:
private void reserve_button_Click(object sender, EventArgs e) {
var form = Application
.OpenForms
.OfType<Form2>()
.LastOrDefault();
if (form == null)
form = new Form2();
form.Show();
//TODO: put the actual number instead of 6
form.MakeReservation(6);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/372181.html
上一篇:檢查c#中的zip是否為空
下一篇:不禁止私人二傳手的訪問
