优雅的技术,可将物品从一个阵列移动到另一个阵列 [英] Elegant technique to move items from one array to another

查看:46
本文介绍了优雅的技术,可将物品从一个阵列移动到另一个阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

内容:纸牌游戏;我想以一种干净的方式将纸牌从卡组中分发给游戏中的每个玩家.

Context: A card game; I want to deal out cards from a deck to each player in the game, in a clean way.

这就是我的想法:

public static CardGame.IGame DealAll(this CardGame.IGame objThis, CardGame.Card[] cards)
    {
        if (objThis.Players.Length > 0)
        {
            for (int i = 0; i < cards.Length; i++)
            {
                objThis.Deck.MoveTo(cards[i], objThis.CurrentPlayer.Hand);

                objThis.AdvancePlayer();
            }
        }

        return objThis;
    }

public static Card[] MoveTo(this Card[] objThis, Card card, Card[] cards)
    {
        List<Card> lstCards = cards.ToList();
        List<Card> lstThis = objThis.ToList();

        lstThis.Remove(card);
        lstCards.Add(card);

        objThis = lstThis.ToArray();
        cards = lstCards.ToArray();

        return cards;
    }

您当然可以看到参考问题.使用ref关键字会导致看起来不太好看的代码,但这可能是不可避免的.有什么建议吗?

Surely you can see the reference problems. Using the ref keyword leads to some not-so-nice looking code, but it may be unavoidable. Any suggestions?

我希望有一个足够灵活的解决方案来处理其他通过卡片"的情况(玩家将卡片放到堆中,将卡片从堆放到垃圾桶"甲板等).

I would prefer a solution that is flexible enough to handle other "card-passing" situations (a player playing a card to the pile, moving cards from the pile to a "trash" deck, etc.).

推荐答案

对于 Array 来说,这是一个糟糕的情况,通常不打算将其重复添加和删除.另外,我不会将其作为扩展方法,因为它在您的应用程序中的少数选定位置之外没有任何意义.

This is a bad case for Arrays, I think, which usually aren't designed to be repeatedly added to and removed from. Also, I would not make this an extension method, since it has no relevance outside of a few selected places in your application.

考虑只是坚持使用List并使用负责执行移动操作的类方法.

Consider just sticking with a List instead and having a class method which is responsible for doing the moving.

public class CardDealer {
...
  private List<Card> _deck;

  // Put the card [c] into [hand], and remove it from the deck.
  public void Deal(List<Card> hand, Card c) {
    _deck.Remove(c);
    hand.Add(c);
  }
}

评论者建议将一副纸牌更好地建模为队列",这是一个合理的点,具体取决于您是否只能从纸牌的顶部取出纸牌.如果确实如此,请考虑以下问题:

Commenters have suggested a deck of cards may better modeled as a Queue, which is a legitimate point depending on whether you can only take cards from the top of the deck or not. If that is indeed the case, consider this:

public class CardDealer {
...
  private Queue<Card> _deck;

  // Put the top card of the deck into the specified hand.
  public void Deal(List<Card> hand) {
    // Deck is a Queue now. No need to specify which card to take.
    Card c = _deck.Dequeue(); 
    hand.Add(c);
  }
}

这篇关于优雅的技术,可将物品从一个阵列移动到另一个阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆