这是我的问题:我正在研究玩家分组(它将玩家分组)。我是通过一个 for 循环来做的,但它并没有划分所有玩家:(。
这是代码:
namespace Grouper
{
public partial class Form1 : Form
{
List<string> players=new List<string>();
public Form1()
{
InitializeComponent();
LoadPlayers();
}
private void But_rnd_Click(object sender, EventArgs e)
{
LoadPlayers();
bool isOdd = players.Count % 2 == 1;
List<string> results=new List<string>();
if(!isOdd) // Count of players is even
{
Grouping(ref results);
}
if(isOdd) // Count of players is odd
{
Grouping(ref results);
results.Add("Remained: " + players[0]);
ShowResults(ref results);
}
}
private void Grouping(ref List<string> results)
{
Random r=new Random();
for (int i = 0; i < players.Count() / 2 + 1; i++)
{
int randomPlr = r.Next(players.Count() / 2 + 1, players.Count());
results.Add(i + 1 + ".: " + players[i] + " + " + players[randomPlr]);
players.RemoveAt(i);
players.RemoveAt(randomPlr - 1);
}
}
private void ShowResults(ref List<string> results)
{
string write = "";
foreach (string result in results)
{
write += result + "\n";
}
MessageBox.Show(write);
}
private void LoadPlayers()
{
players.Clear();
players.Add("p1");
players.Add("p2");
players.Add("p3");
players.Add("p4");
players.Add("p5");
players.Add("p6");
players.Add("p7");
}
}
}
ShowResults() 方法仅显示 2 个组和 1 个剩余的玩家(2 个组和 1 个剩余 = 5 个玩家,但我有 7 个玩家!)。