Android 21点


0x0000 写在前面

  • 在写这个游戏之前,只是模糊地记得文曲星上的21点游戏规则
    想当然地认为就是一个先后发牌然后开牌比大小的游戏
    结果百度一下,发现玩法比我想的复杂不少
    这个demo里删掉了分牌的功能,并且只支持单人游戏
  • 转载请注明
    作者和平北路
    原文点击链接

0x0001 功能简介

  • 庄家发牌
  • 玩家发牌
  • 玩家选择发牌/停牌/放弃
  • 比较大小

0x0002 工程结构

UML类图
  • Card是最基本的卡牌对象,包含花色(Suit)和大小(Rank)两个属性
  • Deck是去掉了大小王的一副牌
  • CardImage是对一张牌的封装,包含了卡牌的内容(Card)和与之绑定的一个视图对象(ImageView),用于在屏幕上进行旋转、移动等动作
  • BitmapUtils是一个工具类,用于从一张包含52张卡牌图案的图片上裁剪对应Card的图片
  • ScreenUtils是一个工具了,用于获取屏幕宽高(只适用于全屏)
  • Rotate3dAnimation是3D旋转动画,请自行百度Android官方源码

0x0003 源码分析

public class Card {

    enum Suit {HEART, SPADE, DIAMOND, CLUB}

    enum Rank {ACE, DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING}

    private Suit suit;
    private Rank rank;

    public Card(Suit suit, Rank rank) {
        this.suit = suit;
        this.rank = rank;
    }

    public Suit getSuit() {
        return suit;
    }

    public Rank getRank() {
        return rank;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || obj.getClass() != getClass()) {
            return false;
        }
        Card card = (Card) obj;
        if (card.suit != suit || card.rank != rank) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int result = suit.ordinal();
        result = 31 * result + rank.ordinal();
        return result;
    }
}
public class Deck {

    Collection<Card.Suit> suits = Arrays.asList(Card.Suit.values());
    Collection<Card.Rank> ranks = Arrays.asList(Card.Rank.values());

    private List<Card> deck = new ArrayList<>();

    public Deck() {
        init();
    }

    private void init() {
        for (Iterator<Card.Suit> i = suits.iterator(); i.hasNext(); /*do nothing*/) {
            Card.Suit suit = i.next();
            for (Iterator<Card.Rank> j = ranks.iterator(); j.hasNext(); /*do nothing*/) {
                deck.add(new Card(suit, j.next()));
            }
        }
    }

    public List<Card> getDeck() {
        return deck;
    }

}

public class CardImage {

    private static final long DURATION = 500L;

    private static final float DEPTH_Z = 0f;

    private int translationX;
    private int translationY;

    private Card card;
    private ImageView image;

    private AnimatorSet animatorSet;
    private IAnimationCallback callback;

    public CardImage(Card card, ImageView image) {
        this.card = card;
        this.image = image;
        translationX = 0;
        translationY = 0;
    }

    public void setCallback(IAnimationCallback callback) {
        this.callback = callback;
    }

    public void translate(final int x, final int y) {
        if (image == null) {
            return;
        }

        if (image.getLeft() == 0 || image.getTop() == 0) {
            final ViewTreeObserver observer = image.getViewTreeObserver();
            observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    translate(x, y);
                    observer.removeOnGlobalLayoutListener(this);
                }
            });
            return;
        }

        if (null != animatorSet) {
            animatorSet.end();
        }
        image.clearAnimation();

        ObjectAnimator animX = ObjectAnimator.ofFloat(image, "translationX", x - image.getLeft());
        ObjectAnimator animY = ObjectAnimator.ofFloat(image, "translationY", y - image.getTop());
        translationX = x - image.getLeft();
        translationY = y - image.getTop();

        animatorSet = new AnimatorSet();
        animatorSet.playTogether(animX, animY);
        animatorSet.setDuration(DURATION);
        animatorSet.start();
        animatorSet.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if (null != callback)
                    callback.onTranslationEnd();
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });
    }

    public void front() {
        if (image == null) {
            return;
        }

        if (null != animatorSet) {
            animatorSet.end();
        }
        image.clearAnimation();

        final int x = image.getLayoutParams().width / 2 + translationX;
        final int y = image.getLayoutParams().height / 2 + translationY;
        Animation firstHalf = rotate(0, 90, x, y);
        firstHalf.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                image.setImageBitmap(BitmapUtils.getCardImage(image.getContext(), card));
                Animation secondHalf = rotate(270, 360, x, y);
                secondHalf.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        if (null != callback)
                            callback.onFrontEnd();
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }
                });
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
    }

    private Animation rotate(float startDegree, float endDegree, float centerX, float centerY) {
        Rotate3dAnimation anim = new Rotate3dAnimation(
                startDegree, endDegree, centerX, centerY, DEPTH_Z, false);
        anim.setDuration(DURATION);
        anim.setFillAfter(true);
        image.startAnimation(anim);
        return anim;
    }

    public Card getCard() {
        return card;
    }

    public ImageView getImage() {
        return image;
    }

    public interface IAnimationCallback {
        void onFrontEnd();

        void onTranslationEnd();
    }

}
public class BitmapUtils {

    public static Bitmap cards;

    public static Bitmap getCardImage(Context context, Card card) {
        if (null == card)
            return null;
        if (null == cards)
            cards = BitmapFactory.decodeResource(context.getResources(), R.drawable.cards);

        int rows = Card.Suit.values().length;
        int cols = Card.Rank.values().length;
        int width = cards.getWidth() / cols;
        int height = cards.getHeight() / rows;
        int x = width * card.getRank().ordinal();
        int y = height * card.getSuit().ordinal();
        return Bitmap.createBitmap(cards, x, y, width, height);
    }

}
public class ScreenUtils {

    private static int sScreenWidth;
    private static int sScreenHeight;

    public static void init(Context context) {
        Resources resources = context.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        sScreenWidth = dm.widthPixels;
        sScreenHeight = dm.heightPixels;
    }

    public static int getScreenWidth(Context context) {
        if (sScreenWidth <= 0) {
            init(context);
        }
        return sScreenWidth;
    }

    public static int getScreenHeight(Context context) {
        if (sScreenHeight <= 0) {
            init(context);
        }
        return sScreenHeight;
    }

}
public class MainActivity extends Activity {

    private static final int MSG_PLAYER_DEAL = 0x00;
    private static final int MSG_PLAYER_HIT = 0x01;
    private static final int MSG_PLAYER_STAND = 0x02;
    private static final int MSG_PLAYER_FOLD = 0x03;
    private static final int MSG_BANKER_DEAL = 0x04;
    private static final int MSG_BANKER_DEAL_HIDE = 0x05;
    private static final int MSG_BANKER_FRONT_HIDE = 0x06;
    private static final int MSG_RESET = 0x07;

    private static final int TEN = 10;
    private static final int BLACK_JACK = 21;

    private static final int CARD_WIDTH = 225;
    private static final int CARD_HEIGHT = 315;
    private static final int CARD_MARGIN = 10;
    private static final int CARD_MARGIN_TOP = 20;
    private static final int CARD_MARGIN_BOTTOM = 500;

    private int screenWidth;
    private int screenHeight;

    private Random random;

    private ViewGroup parent;
    private View hit;
    private View stand;
    private View fold;

    private List<Card> cards;
    private List<CardImage> playerCards;
    private List<CardImage> bankerCards;

    private Handler msgHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            switch (what) {
                case MSG_PLAYER_DEAL:
                    dealPlayer();
                    break;
                case MSG_BANKER_DEAL:
                    dealBanker();
                    break;
                case MSG_BANKER_DEAL_HIDE:
                    dealBankerHide();
                    break;
                case MSG_BANKER_FRONT_HIDE:
                    frontBankerHide();
                    break;
                case MSG_PLAYER_HIT:
                    hit();
                    break;
                case MSG_PLAYER_STAND:
                    stand();
                    break;
                case MSG_PLAYER_FOLD:
                    fold();
                    break;
                case MSG_RESET:
                    reset();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        ScreenUtils.init(getApplicationContext());
        setContentView(R.layout.activity_main);

        screenWidth = ScreenUtils.getScreenWidth(this);
        screenHeight = ScreenUtils.getScreenHeight(this);

        random = new Random();
        cards = new Deck().getDeck();
        playerCards = new ArrayList<>();
        bankerCards = new ArrayList<>();

        parent = (ViewGroup) findViewById(R.id.activity_main);

        hit = findViewById(R.id.hit);
        hit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hit();
            }
        });
        stand = findViewById(R.id.stand);
        stand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stand();
            }
        });
        fold = findViewById(R.id.fold);
        fold.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fold();
            }
        });

        deal();
    }

    private void deal() {
        disableButtons();
        msgHandle.sendMessageDelayed(Message.obtain(msgHandle, MSG_PLAYER_DEAL), 500);
        msgHandle.sendMessageDelayed(Message.obtain(msgHandle, MSG_BANKER_DEAL), 2000);
        msgHandle.sendMessageDelayed(Message.obtain(msgHandle, MSG_PLAYER_DEAL), 3500);
        msgHandle.sendMessageDelayed(Message.obtain(msgHandle, MSG_BANKER_DEAL_HIDE), 5000);
    }

    private void dealPlayer() {
        disableButtons();
        CardImage player = new CardImage(
                cards.remove(random.nextInt(cards.size())),
                createCardImage());
        player.setCallback(new CardImage.IAnimationCallback() {
            @Override
            public void onFrontEnd() {
                updatePlayerCardsLocation();
            }

            @Override
            public void onTranslationEnd() {
                if (playerCards.size() >= 2) {
                    enableButtons();
                }
                if (playerCards.size() > 2) {
                    check();
                }
            }
        });
        player.front();
        playerCards.add(player);
    }

    private void dealBanker() {
        disableButtons();
        CardImage banker = new CardImage(
                cards.remove(random.nextInt(cards.size())),
                createCardImage());
        banker.setCallback(new CardImage.IAnimationCallback() {
            @Override
            public void onFrontEnd() {
                updateBankerCardsLocation();
            }

            @Override
            public void onTranslationEnd() {
                if (bankerCards.size() > 2) {
                    disableButtons();
                    if (!check()) {
                        if (count(bankerCards) > count(playerCards)) {
                            lose();
                        } else {
                            msgHandle.sendMessageDelayed(Message.obtain(msgHandle, MSG_BANKER_DEAL), 2000);
                        }
                    }
                }
            }
        });
        banker.front();
        bankerCards.add(banker);
    }

    private void dealBankerHide() {
        disableButtons();
        CardImage banker = new CardImage(
                cards.remove(random.nextInt(cards.size())),
                createCardImage());
        banker.setCallback(new CardImage.IAnimationCallback() {
            @Override
            public void onFrontEnd() {
            }

            @Override
            public void onTranslationEnd() {
                check();
            }
        });
        bankerCards.add(banker);
        updateBankerCardsLocation();
    }

    private void frontBankerHide() {
        disableButtons();
        CardImage banker = bankerCards.get(1);
        banker.front();
    }

    private ImageView createCardImage() {
        ImageView card = new ImageView(this);
        card.setImageResource(R.drawable.card_back);
        card.setScaleType(ImageView.ScaleType.CENTER_CROP);
        RelativeLayout.LayoutParams layoutParams =
                new RelativeLayout.LayoutParams(CARD_WIDTH, CARD_HEIGHT);
        layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        layoutParams.rightMargin = 40;
        parent.addView(card, layoutParams);
        return card;
    }

    private int[] getPlayerCardLocation(int num) {
        int centerX = screenWidth / 2;
        int size = playerCards.size();
        int x = centerX
                - ((size - 1) * CARD_MARGIN + size * CARD_WIDTH) / 2
                + num * (CARD_MARGIN + CARD_WIDTH);
        int y = screenHeight - CARD_MARGIN_BOTTOM;
        return new int[]{x, y};
    }

    private void updatePlayerCardsLocation() {
        int size = playerCards.size();
        for (int i = 0; i < size; i++) {
            int[] location = getPlayerCardLocation(i);
            CardImage cardImage = playerCards.get(i);
            cardImage.translate(location[0], location[1]);
        }
    }

    private int[] getBankerCardLocation(int num) {
        int centerX = screenWidth / 2;
        int size = bankerCards.size();
        int x = centerX
                - ((size - 1) * CARD_MARGIN + size * CARD_WIDTH) / 2
                + num * (CARD_MARGIN + CARD_WIDTH);
        int y = CARD_MARGIN_TOP;
        return new int[]{x, y};
    }

    private void updateBankerCardsLocation() {
        int size = bankerCards.size();
        for (int i = 0; i < size; i++) {
            int[] location = getBankerCardLocation(i);
            CardImage cardImage = bankerCards.get(i);
            cardImage.translate(location[0], location[1]);
        }
    }

    private boolean check() {
        boolean isBankerBlackJack = isBlackJack(bankerCards);
        boolean isPlayerBlackJack = isBlackJack(playerCards);
        if (isBusted(playerCards) || (isBankerBlackJack && !isPlayerBlackJack)) {
            lose();
            return true;
        } else if (isBusted(bankerCards) || (!isBankerBlackJack && isPlayerBlackJack)) {
            win();
            return true;
        } else if (isBankerBlackJack && isPlayerBlackJack) {
            draw();
            return true;
        }
        return false;
    }

    private boolean isBlackJack(List<CardImage> handCards) {
        return count(handCards) == BLACK_JACK;
    }

    private boolean isBusted(List<CardImage> handCards) {
        return count(handCards) > BLACK_JACK;
    }

    private int count(List<CardImage> handCards) {
        int total = 0;
        if (null == handCards) {
            return total;
        }
        for (CardImage cardImage : handCards) {
            if (cardImage == null || cardImage.getCard() == null) {
                continue;
            }
            Card card = cardImage.getCard();
            if (card.getRank() == Card.Rank.ACE) {
                if (total + 11 > BLACK_JACK) {
                    total += 1;
                } else {
                    total += 11;
                }
            } else if (card.getRank().ordinal() >= 9) {
                total += TEN;
            } else {
                total += (card.getRank().ordinal() + 1);
            }
        }
        return total;
    }

    private void reset() {
        cards = new Deck().getDeck();
        for (CardImage cardImage : playerCards) {
            if (cardImage != null && cardImage.getImage() != null) {
                parent.removeView(cardImage.getImage());
            }
        }
        for (CardImage cardImage : bankerCards) {
            if (cardImage != null && cardImage.getImage() != null) {
                parent.removeView(cardImage.getImage());
            }
        }
        playerCards.clear();
        bankerCards.clear();
        for (int i = 0; i < 8; i++) {
            msgHandle.removeMessages(i);
        }
        deal();
    }

    private void enableButtons() {
        hit.setClickable(true);
        stand.setClickable(true);
        fold.setClickable(true);
    }

    private void disableButtons() {
        hit.setClickable(false);
        stand.setClickable(false);
        fold.setClickable(false);
    }

    private void hit() {
        disableButtons();
        msgHandle.sendMessage(Message.obtain(msgHandle, MSG_PLAYER_DEAL));
    }

    private void stand() {
        disableButtons();
        if (count(bankerCards) > count(playerCards)) {
            lose();
            return;
        }
        msgHandle.sendMessage(Message.obtain(msgHandle, MSG_BANKER_DEAL));
    }

    private void fold() {
        disableButtons();
        frontBankerHide();
        lose();
    }

    private void win() {
        disableButtons();
        Toast.makeText(MainActivity.this, "you win!", Toast.LENGTH_SHORT).show();
        msgHandle.sendMessage(Message.obtain(msgHandle, MSG_BANKER_FRONT_HIDE));
        msgHandle.sendMessageDelayed(Message.obtain(msgHandle, MSG_RESET), 4000);
    }

    private void lose() {
        disableButtons();
        Toast.makeText(MainActivity.this, "you lose!", Toast.LENGTH_SHORT).show();
        msgHandle.sendMessage(Message.obtain(msgHandle, MSG_BANKER_FRONT_HIDE));
        msgHandle.sendMessageDelayed(Message.obtain(msgHandle, MSG_RESET), 4000);
    }

    private void draw() {
        disableButtons();
        Toast.makeText(MainActivity.this, "game draws!", Toast.LENGTH_SHORT).show();
        msgHandle.sendMessage(Message.obtain(msgHandle, MSG_BANKER_FRONT_HIDE));
        msgHandle.sendMessageDelayed(Message.obtain(msgHandle, MSG_RESET), 4000);
    }

}

其实源码没有什么技术难点:

  • 所有的动作都以Message方式传递给Handler处理,Handler分发事件调用各个方法
  • 每发一张牌,都是在屏幕上new了一个ImageView,并对这个ImageView进行动画操作
  • 自认为写的比较挫的是对连续动画实现的不好,现在的硬编码low爆了。一个AnimationListener嵌套另一个AnimationListener,而且还需要添加Callback监听旋转和移动动画完成后的下一个操作,更好的实现方式是单起Thread,利用sleep或者wait/notify来实现动画的衔接
  • Animator的使用没有想的简单,说是会改变View属性,但连续使用“translation”操作,View对象的边界其实没有改变,后续的传值需要考虑之前的translation赋值,或者在每次动画之后调用View.layout方法更新一遍边界

0x0004 写码感想

  • 像Handler、Animator这些东西自以为源码看了几遍应该手到擒来的,在使用的时候还是会发现各种效果实现和自己想的不一样
  • 行胜于言
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 201,312评论 5 473
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,578评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 148,337评论 0 333
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,134评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,161评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,303评论 1 280
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,761评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,421评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,609评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,450评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,504评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,194评论 3 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,760评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,836评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,066评论 1 257
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,612评论 2 348
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,178评论 2 341

推荐阅读更多精彩内容