c#中,用计算机模拟洗牌分发给四个玩家,并将四个玩家的牌显示出来
时间: 2024-09-26 13:11:32 浏览: 33
C#实现随机洗牌的方法
在 C# 中,你可以使用 List 或者数组来代表牌堆,然后通过随机数生成器来模拟洗牌和分配的过程。这里是一个简单的例子,我们将使用 List 来表示牌堆并将其分配给四个玩家:
```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
// 初始化一副扑克牌
int deckSize = 52; // 简单假设只有标准的52张牌
List<int> deck = new List<int>(Enumerable.Range(1, deckSize));
// 洗牌
Shuffle(deck);
// 分配给四个玩家
int numPlayers = 4;
List<List<int>> playersCards = new List<List<int>>(numPlayers);
for (int i = 0; i < numPlayers; i++)
{
playersCards.Add(new List<int>());
}
SplitDeck(deck, playersCards);
// 显示每个玩家的牌
foreach (var player in playersCards)
{
Console.WriteLine("Player {0}:", i + 1);
foreach (int card in player)
{
Console.Write(card + " ");
}
Console.WriteLine();
}
Console.ReadLine(); // 阻塞程序,直到按下回车键
}
// 混合列表元素
static void Shuffle(List<int> deck)
{
Random random = new Random();
for (int i = deck.Count - 1; i > 0; i--)
{
int j = random.Next(i + 1);
// 交换deck[i]和deck[j]
int temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
}
// 将牌堆均匀分成四个部分
static void SplitDeck(List<int> deck, List<List<int>> playersCards)
{
int cardsPerPlayer = deck.Count / numPlayers;
for (int i = 0; i < cardsPerPlayer; i++)
{
playersCards[i].Add(deck[i]);
}
// 如果有剩余的牌,随机分配
if (deck.Count % numPlayers != 0)
{
Random rand = new Random();
for (int i = cardsPerPlayer, extraIndex = 0; i < deck.Count; i++, extraIndex = (extraIndex + 1) % numPlayers)
{
playersCards[extraIndex].Add(deck[i]);
}
}
}
}
```
阅读全文