今天看到一個面試題,要你將52張撲克(除大小王),實現發牌功能,平均分給玩家,玩家數量自定義。
回家簡單寫了一個demo,希望可以幫到大家
private string[] poker = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };
private List<String> apokerList = new List<string>();
/// <summary>
/// 初始化一副牌
///
/// </summary>
private void init()
{
int type = 0;
for (int i = 0; i < 52; i++)
{
if (i % 13 == 0)
type++;
String poker = setPokerType(type, i);
apokerList.Add(poker);
}
listRandom();
}
/// <summary>
/// 設置牌面花色
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private String setPokerType(int type, int i)
{
switch (type)
{
case 1:
return "黑桃" + poker[i];
case 2:
return "紅桃" + poker[i - 13];
case 3:
return "方塊" + poker[i - 26];
case 4:
return "梅花" + poker[i - 39];
}
return "";
}
/// <summary>
/// 打亂牌堆
/// </summary>
/// <returns></returns>
private void listRandom()
{
Random ran = new Random();
List<String> newList = new List<String>();
int index = 0;
String temp = "";
for (int i = 0; i < apokerList.Count; i++)
{
index = ran.Next(0, apokerList.Count - 1);
if (index != i)
{
temp = apokerList[i];
apokerList[i] = apokerList[index];
apokerList[index] = temp;
pokerTB.Text += apokerList[i] + "--";
}
}
}
/// <summary>
/// 給玩家發牌
/// </summary>
/// <param name="player"></param>
private void licensing(int player)
{
int everyonePoker = apokerList.Count / player;
for (int i = 0; i < apokerList.Count; i++)
{
if (i % everyonePoker == 0)
{
playerTB.Text += "正在發牌給玩家" + i + "-------:";
}
playerTB.Text += apokerList[i] + " ";
}
}