甲乙丙丁4 人排序:随机产生 4 人的拿牌顺序,出牌顺序与拿牌顺序相同 用C#实现
时间: 2024-04-21 07:23:11 浏览: 189
要实现随机产生甲乙丙丁四人的拿牌顺序,并且保持出牌顺序与拿牌顺序相同,可以使用 Fisher-Yates 洗牌算法。以下是使用C#实现的代码示例:
```csharp
using System;
using System.Collections.Generic;
public class Player
{
public string Name { get; set; }
public Player(string name)
{
Name = name;
}
}
public class Game
{
private List<Player> players;
public Game()
{
players = new List<Player>();
// 初始化四个玩家
InitializePlayers();
}
public void StartGame()
{
// 随机排序玩家
ShufflePlayers();
// 打印出牌顺序
PrintPlayOrder();
}
private void InitializePlayers()
{
string[] names = { "甲", "乙", "丙", "丁" };
foreach (string name in names)
{
players.Add(new Player(name));
}
}
private void ShufflePlayers()
{
Random random = new Random();
int n = players.Count;
while (n > 1)
{
n--;
int k = random.Next(n + 1);
Player player = players[k];
players[k] = players[n];
players[n] = player;
}
}
private void PrintPlayOrder()
{
Console.WriteLine("出牌顺序如下:");
foreach (Player player in players)
{
Console.WriteLine(player.Name);
}
}
}
public class Program
{
public static void Main(string[] args)
{
Game game = new Game();
game.StartGame();
}
}
```
这段代码实现了随机产生甲乙丙丁四人的拿牌顺序,并且保持出牌顺序与拿牌顺序相同。在 `ShufflePlayers` 方法中使用 Fisher-Yates 洗牌算法来随机排序玩家列表。然后,通过 `PrintPlayOrder` 方法打印出牌顺序。
运行该代码,您将看到每次输出的出牌顺序都是随机的,但每个玩家的出牌顺序是一致的。
阅读全文