C# 如何通过单击 Form1 上的按钮随机化 Form 2 中按钮的颜色

C# How to randomize a color on buttons in Form 2 from clicking a button on Form1

我正在构建一个 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();
}

Movie Menu Picture Seating Selection

嗯,你应该 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);
}