使用SuperSocket开发联网斗地主(一):发牌

实现思路:

将整幅牌数据和发牌数据都在服务端完成,客户端只存储自己的牌和底牌

一、服务端:

抽出一个牌类:

public class DouDiZhuGameCard
{
     public string CardColor { get; set; }
     public string CardName { get; set; }
     public int CardValue { get; set; }
}

分别表示花色,名称和值,值用来比较大小,然后把54张牌初始化进去。继续打乱这54张牌的顺序:

Random random = new Random();
var cards = DouDiZhuGameConfig.DoDiZhuCards;
for (int i = 0; i < cards.Count; i++)
{
     DouDiZhuGameCard temp;
     int j = random.Next(0, cards.Count - 1);
     temp = cards[j];
     cards[j] = cards[i];
     cards[i] = temp;
}

然后分发给3个玩家:

int playerIndex = 1;
foreach (var item in DouDiZhuGameConfig.UserList)
{
     item.Value.MyCards = cards.Skip((playerIndex-1)*17).Take(17).ToList();
     item.Value.MyCards.Sort((x, y) => x.CardValue.CompareTo(y.CardValue));

    item.Value.CommonCards= cards.Skip(51).Take(3).ToList();

    for (int i = 0; i < DouDiZhuGameConfig.MaxCard; i++)
     {
         item.Value.OtherPlayerCards.Add(new DouDiZhuGameCard { CardColor="",CardName="",CardValue=0});
     }

    response.Add(item.Key,item.Value);
     playerIndex++;
}

分给自己的是有数据的,用来在客户端显示,分给另外两家的是空数据(当然可以在客户端实现),另外把底牌也初始化,每个客户端都能看到。

然后根据scoketsession分发下去:

var result = GameManager.SendCardToPlayer();
foreach (var playerInfo in result)
{
     var play_session = webSocketServer.GetSessionByID(playerInfo.Key);
    
     ResponseModel<DouDiZhuUserInfoModel> res_sendCard = new ResponseModel<DouDiZhuUserInfoModel>();
     res_sendCard.Action = "sendcard";
     res_sendCard.Data = playerInfo.Value;

    if(session.SessionID==playerInfo.Key)//是我
     {
         res_sendCard.Data.MyCards = playerInfo.Value.MyCards;
         res_sendCard.Data.OtherPlayerCards = playerInfo.Value.OtherPlayerCards;
     }
     this.SendMessage(play_session, JsonConvert.SerializeObject(res_sendCard));

}

 

二、客户端:

在收到服务端通知的“startgame”之后显示每个玩家的牌:

player1=userData.OtherPlayerCards;

player2=userData.OtherPlayerCards;

player_me=userData.MyCards;

diPai=userData.CommonCards;

然后按照位置显示出来即可。

最终效果如图:

使用SuperSocket开发联网斗地主(一):发牌

使用SuperSocket开发联网斗地主(一):发牌

使用SuperSocket开发联网斗地主(一):发牌

使用SuperSocket开发联网斗地主(一):发牌

代码下载

上一篇:【题解】ABC225F - String Cards


下一篇:CF1392H ZS Shuffles Cards