2016-04-08 3 views
0

Я пытаюсь создать установочный интерфейс для программы, которая имитирует настольную игру на C#. У меня есть 1 ComboBox, который позволяет пользователю выбирать количество игроков, которое, в свою очередь, скрывает или отображает выбранное количество combobox. Каждый из списков должен иметь все четыре варианта (красный, синий, зеленый, желтый), однако, когда цвет выбран из одного поля, он должен удалить эту опцию из остальных списков (например, если игрок1 выбирает красный, тогда игроки 2-4 должны также не может выбрать красный). Прямо сейчас я пытаюсь использовать несколько списков для отображения информации в каждом поле со списком, но код, который я написал для удаления цветов из оставшихся списков, привел к ряду непреднамеренных последствий. Мне интересно, есть ли лучший способ обмена данными между всеми списками. Любая помощь/идеи были бы высоко оценены!Как настроить несколько комбинированных ящиков с одним и тем же источником данных?

Я приложил свой код ниже, чтобы дать вам лучшее представление о том, с чем я работаю. Спасибо за ваше время!

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace StartPage.CS 
{ 
    public partial class SetUp : Form 
    { 
     // Create a static array to hold the players 
     public static Player[] players { get; private set; } 

     // create lists to hold the colors for each player 
     List<String> player1Colors = new List<String>(); 
     List<String> player2Colors = new List<String>(); 
     List<String> player3Colors = new List<String>(); 
     List<String> player4Colors = new List<String>(); 


     public SetUp() 
     { 
      InitializeComponent(); 
     } 

     private void SetUp_Load(object sender, EventArgs e) 
     { 
      // initialize the selected index to 2 players 
      cboSelectPlayers.SelectedIndex = 0; 

      // add the colors to each list 
      player1Colors.Add("Red"); 
      player1Colors.Add("Blue"); 
      player1Colors.Add("Green"); 
      player1Colors.Add("Yellow"); 

      player2Colors.Add("Red"); 
      player2Colors.Add("Blue"); 
      player2Colors.Add("Green"); 
      player2Colors.Add("Yellow"); 

      player3Colors.Add("Red"); 
      player3Colors.Add("Blue"); 
      player3Colors.Add("Green"); 
      player3Colors.Add("Yellow"); 

      player4Colors.Add("Red"); 
      player4Colors.Add("Blue"); 
      player4Colors.Add("Green"); 
      player4Colors.Add("Yellow"); 

      // add each list to it's respective comboBox 
      for (int i = 0; i < player1Colors.Count; ++i) 
      { 
       cboPlayer1Color.Items.Add(player1Colors[i]); 
      } 
      for (int i = 0; i < player2Colors.Count; ++i) 
      { 
       cboPlayer2Color.Items.Add(player2Colors[i]); 
      } 
      for (int i = 0; i < player3Colors.Count; ++i) 
      { 
       cboPlayer3Color.Items.Add(player3Colors[i]); 
      } 
      for (int i = 0; i < player4Colors.Count; ++i) 
      { 
       cboPlayer4Color.Items.Add(player4Colors[i]); 
      } 
     } 

     // method to create the players and add them to the array 


     // handles displaying the number of players to select colors 
     private void cboSelectPlayers_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      if (cboSelectPlayers.SelectedIndex == 0) // if players = 2 
      { 
       lblPlayer3Select.Hide(); 
       cboPlayer3Color.Hide(); 
       lblPlayer4Select.Hide(); 
       cboPlayer4Color.Hide(); 
      } 
      else if (cboSelectPlayers.SelectedIndex == 1) // if players = 3 
      { 
       lblPlayer3Select.Show(); 
       cboPlayer3Color.Show(); 
       lblPlayer4Select.Hide(); 
       cboPlayer4Color.Hide(); 
      } 
      else if (cboSelectPlayers.SelectedIndex == 2) // if players 4 
      { 
       lblPlayer3Select.Show(); 
       cboPlayer3Color.Show(); 
       lblPlayer4Select.Show(); 
       cboPlayer4Color.Show(); 
      } 
     } 

     // handles removing player1's selected color from other comboboxes 
     private void cboPlayer1Color_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      if (cboPlayer1Color.SelectedItem == "Red") 
      { 
       // remove red from the other comboboxes 
       player2Colors.Remove("Red"); 
       player3Colors.Remove("Red"); 
       player4Colors.Remove("Red"); 

       // make sure that the other colors that are supposed to be there are 
       if (!player2Colors.Contains("Blue") && !player3Colors.Contains("Blue") && !player4Colors.Contains("Blue")) 
       { 
        player2Colors.Add("Blue"); 
        player3Colors.Add("Blue"); 
        player4Colors.Add("Blue"); 
       } 
       if (!player2Colors.Contains("Yellow") && !player3Colors.Contains("Yellow") && !player4Colors.Contains("Yellow")) 
       { 
        player2Colors.Add("Yellow"); 
        player3Colors.Add("Yellow"); 
        player4Colors.Add("Yellow"); 
       } 
       if (!player2Colors.Contains("Green") && !player3Colors.Contains("Green") && !player4Colors.Contains("Green")) 
       { 
        player2Colors.Add("Green"); 
        player3Colors.Add("Green"); 
        player4Colors.Add("Green"); 
       } 
      } 
      else if (cboPlayer1Color.SelectedItem == "Blue") 
      { 
       // remove blue from the other comboboxes 
       player2Colors.Remove("Blue"); 
       player3Colors.Remove("Blue"); 
       player4Colors.Remove("Blue"); 

       // make sure that the other colors that are supposed to be there are 
       if (!player2Colors.Contains("Red") && !player3Colors.Contains("Red") && !player4Colors.Contains("Red")) 
       { 
        player2Colors.Add("Red"); 
        player3Colors.Add("Red"); 
        player4Colors.Add("Red"); 
       } 
       if (!player2Colors.Contains("Yellow") && !player3Colors.Contains("Yellow") && !player4Colors.Contains("Yellow")) 
       { 
        player2Colors.Add("Yellow"); 
        player3Colors.Add("Yellow"); 
        player4Colors.Add("Yellow"); 
       } 
       if (!player2Colors.Contains("Green") && !player3Colors.Contains("Green") && !player4Colors.Contains("Green")) 
       { 
        player2Colors.Add("Green"); 
        player3Colors.Add("Green"); 
        player4Colors.Add("Green"); 
       } 
      } 
      else if (cboPlayer1Color.SelectedItem == "Yellow") 
      { 
       // remove yellow from the other comboboxes 
       player2Colors.Remove("Yellow"); 
       player3Colors.Remove("Yellow"); 
       player4Colors.Remove("Yellow"); 

       // make sure that the other colors that are supposed to be there are 
       if (!player2Colors.Contains("Red") && !player3Colors.Contains("Red") && !player4Colors.Contains("Red")) 
       { 
        player2Colors.Add("Red"); 
        player3Colors.Add("Red"); 
        player4Colors.Add("Red"); 
       } 
       if (!player2Colors.Contains("Blue") && !player3Colors.Contains("Blue") && !player4Colors.Contains("Blue")) 
       { 
        player2Colors.Add("Blue"); 
        player3Colors.Add("Blue"); 
        player4Colors.Add("Blue"); 
       } 
       if (!player2Colors.Contains("Green") && !player3Colors.Contains("Green") && !player4Colors.Contains("Green")) 
       { 
        player2Colors.Add("Green"); 
        player3Colors.Add("Green"); 
        player4Colors.Add("Green"); 
       } 
      } 
      else if (cboPlayer1Color.SelectedItem == "Green") 
      { 
       // remove green from the other comboboxes 
       player2Colors.Remove("Green"); 
       player3Colors.Remove("Green"); 
       player4Colors.Remove("Green"); 

       // make sure that the other colors that are supposed to be there are 
       if (!player2Colors.Contains("Red") && !player3Colors.Contains("Red") && !player4Colors.Contains("Red")) 
       { 
        player2Colors.Add("Red"); 
        player3Colors.Add("Red"); 
        player4Colors.Add("Red"); 
       } 
       if (!player2Colors.Contains("Blue") && !player3Colors.Contains("Blue") && !player4Colors.Contains("Blue")) 
       { 
        player2Colors.Add("Blue"); 
        player3Colors.Add("Blue"); 
        player4Colors.Add("Blue"); 
       } 
       if (!player2Colors.Contains("Yellow") && !player3Colors.Contains("Yellow") && !player4Colors.Contains("Yellow")) 
       { 
        player2Colors.Add("Yellow"); 
        player3Colors.Add("Yellow"); 
        player4Colors.Add("Yellow"); 
       } 
      } 
      // clear and then update the other comboboxes 
      cboPlayer2Color.Items.Clear(); 
      cboPlayer3Color.Items.Clear(); 
      cboPlayer4Color.Items.Clear(); 
      for (int i = 0; i < player2Colors.Count; ++i) 
      { 
       cboPlayer2Color.Items.Add(player2Colors[i]); 
      } 
      for (int i = 0; i < player3Colors.Count; ++i) 
      { 
       cboPlayer3Color.Items.Add(player3Colors[i]); 
      } 
      for (int i = 0; i < player4Colors.Count; ++i) 
      { 
       cboPlayer4Color.Items.Add(player4Colors[i]); 
      } 
     } 

     // handles removing player2's selected color from other comboboxes 
     private void cboPlayer2Color_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      if (cboPlayer2Color.SelectedItem == "Red") 
      { 
       // remove red from the other comboboxes 
       player1Colors.Remove("Red"); 
       player3Colors.Remove("Red"); 
       player4Colors.Remove("Red"); 

       // make sure that the other colors that are supposed to be there are 
       if (!player1Colors.Contains("Blue") && !player3Colors.Contains("Blue") && !player4Colors.Contains("Blue")) 
       { 
        player1Colors.Add("Blue"); 
        player3Colors.Add("Blue"); 
        player4Colors.Add("Blue"); 
       } 
       if (!player1Colors.Contains("Yellow") && !player3Colors.Contains("Yellow") && !player4Colors.Contains("Yellow")) 
       { 
        player1Colors.Add("Yellow"); 
        player3Colors.Add("Yellow"); 
        player4Colors.Add("Yellow"); 
       } 
       if (!player1Colors.Contains("Green") && !player3Colors.Contains("Green") && !player4Colors.Contains("Green")) 
       { 
        player1Colors.Add("Green"); 
        player3Colors.Add("Green"); 
        player4Colors.Add("Green"); 
       } 
      } 
      else if (cboPlayer2Color.SelectedItem == "Blue") 
      { 
       // remove blue from the other comboboxes 
       player1Colors.Remove("Blue"); 
       player3Colors.Remove("Blue"); 
       player4Colors.Remove("Blue"); 

       // make sure that the other colors that are supposed to be there are 
       if (!player1Colors.Contains("Red") && !player3Colors.Contains("Red") && !player4Colors.Contains("Red")) 
       { 
        player1Colors.Add("Red"); 
        player3Colors.Add("Red"); 
        player4Colors.Add("Red"); 
       } 
       if (!player1Colors.Contains("Yellow") && !player3Colors.Contains("Yellow") && !player4Colors.Contains("Yellow")) 
       { 
        player1Colors.Add("Yellow"); 
        player3Colors.Add("Yellow"); 
        player4Colors.Add("Yellow"); 
       } 
       if (!player1Colors.Contains("Green") && !player3Colors.Contains("Green") && !player4Colors.Contains("Green")) 
       { 
        player1Colors.Add("Green"); 
        player3Colors.Add("Green"); 
        player4Colors.Add("Green"); 
       } 
      } 
      else if (cboPlayer2Color.SelectedItem == "Yellow") 
      { 
       // remove yellow from the other comboboxes 
       player1Colors.Remove("Yellow"); 
       player3Colors.Remove("Yellow"); 
       player4Colors.Remove("Yellow"); 

       // make sure that the other colors that are supposed to be there are 
       if (!player1Colors.Contains("Red") && !player3Colors.Contains("Red") && !player4Colors.Contains("Red")) 
       { 
        player1Colors.Add("Red"); 
        player3Colors.Add("Red"); 
        player4Colors.Add("Red"); 
       } 
       if (!player1Colors.Contains("Blue") && !player3Colors.Contains("Blue") && !player4Colors.Contains("Blue")) 
       { 
        player1Colors.Add("Blue"); 
        player3Colors.Add("Blue"); 
        player4Colors.Add("Blue"); 
       } 
       if (!player1Colors.Contains("Green") && !player3Colors.Contains("Green") && !player4Colors.Contains("Green")) 
       { 
        player1Colors.Add("Green"); 
        player3Colors.Add("Green"); 
        player4Colors.Add("Green"); 
       } 
      } 
      else if (cboPlayer2Color.SelectedItem == "Green") 
      { 
       // remove green from the other comboboxes 
       player1Colors.Remove("Green"); 
       player3Colors.Remove("Green"); 
       player4Colors.Remove("Green"); 

       // make sure that the other colors that are supposed to be there are 
       if (!player1Colors.Contains("Red") && !player3Colors.Contains("Red") && !player4Colors.Contains("Red")) 
       { 
        player1Colors.Add("Red"); 
        player3Colors.Add("Red"); 
        player4Colors.Add("Red"); 
       } 
       if (!player1Colors.Contains("Blue") && !player3Colors.Contains("Blue") && !player4Colors.Contains("Blue")) 
       { 
        player1Colors.Add("Blue"); 
        player3Colors.Add("Blue"); 
        player4Colors.Add("Blue"); 
       } 
       if (!player1Colors.Contains("Yellow") && !player3Colors.Contains("Yellow") && !player4Colors.Contains("Yellow")) 
       { 
        player1Colors.Add("Yellow"); 
        player3Colors.Add("Yellow"); 
        player4Colors.Add("Yellow"); 
       } 
      } 
      // clear and then update the other comboboxes 
      cboPlayer1Color.Items.Clear(); 
      cboPlayer3Color.Items.Clear(); 
      cboPlayer4Color.Items.Clear(); 
      for (int i = 0; i < player2Colors.Count; ++i) 
      { 
       cboPlayer2Color.Items.Add(player2Colors[i]); 
      } 
      for (int i = 0; i < player3Colors.Count; ++i) 
      { 
       cboPlayer3Color.Items.Add(player3Colors[i]); 
      } 
      for (int i = 0; i < player4Colors.Count; ++i) 
      { 
       cboPlayer4Color.Items.Add(player4Colors[i]); 
      } 
     } 

     // handles removing player3's selected color from other comboboxes 
     private void cboPlayer3Color_SelectedIndexChanged(object sender, EventArgs e) 
     { 

     } 

     // handles removing player4's selected color from other comboboxes 
     private void cboPlayer4Color_SelectedIndexChanged(object sender, EventArgs e) 
     { 

     } 

     /* method to update the comboBoxes 
     private void updateComboBoxes() 
     { 
      for (int i = 0; i < player1Colors.Count; ++i) 
      { 
       cboPlayer1Color.Items.Add(player1Colors[i]); 
      } 
      for (int i = 0; i < player2Colors.Count; ++i) 
      { 
       cboPlayer2Color.Items.Add(player2Colors[i]); 
      } 
      for (int i = 0; i < player3Colors.Count; ++i) 
      { 
       cboPlayer3Color.Items.Add(player3Colors[i]); 
      } 
      for (int i = 0; i < player4Colors.Count; ++i) 
      { 
       cboPlayer4Color.Items.Add(player4Colors[i]); 
      } 
     }*/ 

     private void btnStart_Click(object sender, EventArgs e) 
     { 
      //Control control = new Control(players); 
      GameBoard gameboard = new GameBoard(); 
      gameboard.ShowDialog(); 
      this.Close(); 
     } 
    } 
} 
+0

Каковы непреднамеренные последствия? Вызывает ли этот код ошибку? Вы действительно не задавали много вопросов. – LarsTech

+0

Непреднамеренные последствия включают: После выбора «Красный» для игрока1, если игрок2 выбрал цвет, выбор игрока1 будет либо пустым (что означает, что он/она не может изменить свое мнение о своем цвете), либо цвета будут повторяться так, чем имея 3 варианта, у игрока1 теперь есть 7 вариантов. Код не вызывает ошибку. – CPratt

ответ

0

Вот как я в конечном итоге делает его (добавили опцию «Select», чтобы сделать его немного более логичным, чтобы «отмените» цвет):

List<string> colors = new List<string>() { "Select", "Red", "Blue", "Green", "Yellow" }; 
List<ComboBox> combos = new List<ComboBox>(); 

public Form1() { 
    InitializeComponent(); 

    combos.AddRange(new ComboBox[] { comboBox1, comboBox2, comboBox3, comboBox4 }); 
    foreach (ComboBox cb in combos) { 
    cb.Items.AddRange(colors.ToArray()); 
    cb.SelectedIndex = 0; 
    cb.SelectedIndexChanged += cb_SelectedIndexChanged; 
    } 
} 

void cb_SelectedIndexChanged(object sender, EventArgs e) { 
    List<string> selectedColors = new List<string>(); 
    foreach (ComboBox cb1 in combos) { 
    if (cb1.SelectedIndex > 0) { 
     selectedColors.Add(cb1.SelectedItem.ToString()); 
    } 
    foreach (ComboBox cb2 in combos.Where(x => !x.Equals(cb1))) { 
     if (cb2.SelectedIndex > 0) { 
     if (cb1.Items.Contains(cb2.SelectedItem.ToString())) { 
      cb1.Items.Remove(cb2.SelectedItem.ToString()); 
     } 
     } 
    } 
    } 

    foreach (ComboBox cb in combos) { 
    foreach (string c in colors) { 
     if (!selectedColors.Contains(c) && !cb.Items.Contains(c)) { 
     cb.Items.Add(c); 
     } 
    } 
    } 
} 

В принципе, логика чтобы получить все цвета, выбранные в список, а затем проверить, отображается ли этот цвет в других списках, и если да, то удалите его. Затем вы возвращаетесь через элементы ComboBox, чтобы увидеть, отсутствует ли какой-либо цвет, и если да, добавьте его обратно.

+0

Большое спасибо! – CPratt

0

В случае, если кто-то еще не знает этого сообщения, я хотел бы опубликовать свой код после включения кода LarsTech.

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace StartPage.CS 
{ 
    public partial class SetUp : Form 
    { 
     // Create a static array to hold the players 
     public static Player[] players { get; private set; } 

     // create lists to hold the colors for each player, as well as the comboBoxes 
     List<String> colors = new List<String> { "Select Color","Red", "Blue", "Yellow", "Green" }; 
     List<ComboBox> combos = new List<ComboBox>(); 

     // constructor 
     public SetUp() 
     { 
      InitializeComponent(); 

      // add colors to ComboBoxes and set the initial index 
      combos.AddRange(new ComboBox[] { cboPlayer1Color, cboPlayer2Color, cboPlayer3Color, cboPlayer4Color }); 
      foreach (ComboBox combo in combos) 
      { 
       combo.Items.AddRange(colors.ToArray()); 
       combo.SelectedIndex = 0; 
       combo.SelectedIndexChanged += combo_SelectedIndexChanged; 
      } 
     } 

     // eventhandling for form load 
     private void SetUp_Load(object sender, EventArgs e) 
     { 
      // initialize the selected index to 2 players 
      cboSelectPlayers.SelectedIndex = 0; 
     } 

     // handles displaying the number of players to select colors 
     private void cboSelectPlayers_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      // reset each combobox to index 0 
      foreach (ComboBox cbox in combos) 
      { 
       cbox.SelectedIndex = 0; 
      } 

      // Hide or Show comboboxes based on how many players are selected 
      if (cboSelectPlayers.SelectedIndex == 0) // if players = 2 
      { 
       lblPlayer3Select.Hide(); 
       cboPlayer3Color.Hide(); 
       lblPlayer4Select.Hide(); 
       cboPlayer4Color.Hide(); 
      } 
      else if (cboSelectPlayers.SelectedIndex == 1) // if players = 3 
      { 
       lblPlayer3Select.Show(); 
       cboPlayer3Color.Show(); 
       lblPlayer4Select.Hide(); 
       cboPlayer4Color.Hide(); 
      } 
      else if (cboSelectPlayers.SelectedIndex == 2) // if players 4 
      { 
       lblPlayer3Select.Show(); 
       cboPlayer3Color.Show(); 
       lblPlayer4Select.Show(); 
       cboPlayer4Color.Show(); 
      } 
     } 

     // handles making sure that the same color can't be used by multiple players 
     public void combo_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      List<String> selectedColors = new List<String>(); 
      foreach (ComboBox cb1 in combos) 
      { 
       if (cb1.SelectedIndex > 0) 
       { 
        selectedColors.Add(cb1.SelectedItem.ToString()); 
       } 

       foreach (ComboBox cb2 in combos.Where(x => !x.Equals(cb1))) 
       { 
        if (cb2.SelectedIndex > 0) 
        { 
         if (cb1.Items.Contains(cb2.SelectedItem.ToString())) 
         { 
          cb1.Items.Remove(cb2.SelectedItem.ToString()); 
         } 
        } 
       } 
      } 

      foreach (ComboBox cb in combos) 
      { 
       foreach (String c in colors) 
       { 
        if (!selectedColors.Contains(c) && !cb.Items.Contains(c)) 
        { 
         cb.Items.Add(c); 
        } 
       } 
      } 
     } 

     // handles form validation 
     private Boolean formValidation() 
     { 
      if (cboSelectPlayers.SelectedItem.ToString() == "2") // if number of players = 2 
      { 
       // display error message if one of the players hasn't selected a color and return false 
       if (cboPlayer1Color.SelectedIndex < 1 || cboPlayer2Color.SelectedIndex < 1) 
       { 
        MessageBox.Show("Please select a color for each player!"); 
        return false; 
       } 
       else 
       { 
        players = new Player[2]; 
        createPlayers(2); 
       } 
      } 
      else if (cboSelectPlayers.SelectedItem.ToString() == "3") // if number of players = 3 
      { 
       // display error message if one of the players hasn't selected a color and return false 
       if (cboPlayer1Color.SelectedIndex < 1 || cboPlayer2Color.SelectedIndex < 1 || cboPlayer3Color.SelectedIndex < 1) 
       { 
        MessageBox.Show("Please select a color for each player!"); 
        return false; 
       } 
       else 
       { 
        players = new Player[3]; 
        createPlayers(3); 
       } 
      } 
      else if (cboSelectPlayers.SelectedItem.ToString() == "4") // number of players = 4 
      { 
       // display error message if one of the players hasn't selected a color and return false 
       if (cboPlayer1Color.SelectedIndex < 1 || cboPlayer2Color.SelectedIndex < 1 || cboPlayer3Color.SelectedIndex < 1 || cboPlayer4Color.SelectedIndex < 1) 
       { 
        MessageBox.Show("Please select a color for each player!"); 
        return false; 
       } 
       else 
       { 
        players = new Player[4]; 
        createPlayers(4); 
       } 
      } 

      // if no errors were found in validation, return true 
      return true; 
     } 

     // create players and add them to the static array 
     private void createPlayers(int numPlayers) 
     { 

      for (int i = 0; i < numPlayers; i++) 
      { 
       if (combos[i].SelectedItem.ToString() == "Red") 
       { 
        players[i] = new Player(Color.Red); 
       } 
       else if (combos[i].SelectedItem.ToString() == "Blue") 
       { 
        players[i] = new Player(Color.Blue); 
       } 
       else if (combos[i].SelectedItem.ToString() == "Yellow") 
       { 
        players[i] = new Player(Color.Yellow); 
       } 
       else if (combos[i].SelectedItem.ToString() == "Green") 
       { 
        players[i] = new Player(Color.Green); 
       } 
      } 
     } 

     private void btnStart_Click(object sender, EventArgs e) 
     { 
      if (formValidation()) 
      { 
       GameBoard gameboard = new GameBoard(); 
       gameboard.ShowDialog(); 
       this.Close(); 
      } 
     }  
    } 
} 
Смежные вопросы

 Смежные вопросы