1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.example.androidx.viewpager2.cards; 18 19 import static java.util.Arrays.asList; 20 import static java.util.Collections.unmodifiableSet; 21 22 import android.os.Bundle; 23 24 import java.util.ArrayList; 25 import java.util.LinkedHashSet; 26 import java.util.List; 27 import java.util.Set; 28 29 /** 30 * Playing card 31 */ 32 public class Card { 33 private static final String ARGS_BUNDLE = Card.class.getName() + ":Bundle"; 34 35 private static final Set<Character> SUITS = unmodifiableSet(new LinkedHashSet<>( 36 asList('♣' /* clubs*/, '♦' /* diamonds*/, '♥' /* hearts*/, '♠' /*spades*/))); 37 private static final Set<Character> VALUES = unmodifiableSet(new LinkedHashSet<>( 38 asList('2', '3', '4', '5', '6', '7', '8', '9', '⒑', 'J', 'Q', 'K', 'A'))); 39 40 private final char mSuit; 41 private final char mValue; 42 Card(char suit, char value)43 public Card(char suit, char value) { 44 this.mSuit = checkValidValue(suit, SUITS); 45 this.mValue = checkValidValue(value, VALUES); 46 } 47 getSuit()48 char getSuit() { 49 return mSuit; 50 } 51 getCornerLabel()52 String getCornerLabel() { 53 return mValue + "\n" + mSuit; 54 } 55 56 /** Use in conjunction with {@link Card#fromBundle(Bundle)} */ toBundle()57 public Bundle toBundle() { 58 Bundle args = new Bundle(1); 59 args.putCharArray(ARGS_BUNDLE, new char[]{mSuit, mValue}); 60 return args; 61 } 62 63 /** Use in conjunction with {@link Card#toBundle()} */ fromBundle(Bundle bundle)64 public static Card fromBundle(Bundle bundle) { 65 char[] spec = bundle.getCharArray(ARGS_BUNDLE); 66 return new Card(spec[0], spec[1]); 67 } 68 checkValidValue(char value, Set<Character> allowed)69 private static char checkValidValue(char value, Set<Character> allowed) { 70 if (allowed.contains(value)) { 71 return value; 72 } 73 throw new IllegalArgumentException("Illegal argument: " + value); 74 } 75 76 /** 77 * Creates a deck of all allowed cards 78 */ createDeck52()79 public static List<Card> createDeck52() { 80 List<Card> result = new ArrayList<>(52); 81 for (Character suit : SUITS) { 82 for (Character value : VALUES) { 83 result.add(new Card(suit, value)); 84 } 85 } 86 if (result.size() != 52) { 87 throw new IllegalStateException(); 88 } 89 return result; 90 } 91 } 92