要求:实现给三个人随机发牌,每人发五张牌,而且显示剩余的牌。
代码:
Card和CardDemo:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
class Card{
public int rank;
public String suit;
public Card(int rank, String suit) {
this.rank = rank;
this.suit = suit;
}
@Override
public String toString() {
return ""+suit +"" +rank ;
}
}
public class CardDemo {
public static final String[] suits={ "♥","♠","♣","♦"};
public List<Card> BuyDeskCard(){ //买牌
List<Card> cards=new ArrayList<>();
for (int i=1;i<=13;i++){
for (int j=0;j<4;j++){
Card card=new Card(i,suits[j]);
cards.add(card);
}
}
return cards;
}
public void shuffle(List<Card> cards){
for(int i=cards.size()-1;i>0;i--){
Random random=new Random();
int index=random.nextInt(i);
swap(cards,index,i);
}
}
private void swap(List<Card> cards,int i,int j){
Card tmp=cards.get(i);
cards.set(i,cards.get(j));
cards.set(j,tmp);
}
public List<List<Card>> test(List<Card> cards){
List<Card> hand1=new ArrayList<>();
List<Card> hand2=new ArrayList<>();
List<Card> hand3=new ArrayList<>();
List<List<Card>> hands=new ArrayList<>();
hands.add(hand1);
hands.add(hand2);
hands.add(hand3);
for (int i=0;i<5;i++){
for (int j=0;j<3;j++){
Card card= cards.remove(0);
hands.get(j).add(card);
}
}
return hands;
}
}
Test:
import java.util.List;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
CardDemo cardDemo = new CardDemo();
List<Card> ret = cardDemo.BuyDeskCard();
cardDemo.shuffle(ret);
List<List<Card>> ret2= cardDemo.test(ret);
for (int i=0;i<ret2.size();i++){
System.out.println("第"+i+"个人的牌:"+ret2.get(i));
}
System.out.println("剩余的牌");
System.out.println(ret);
}
}
实现效果:每次运行的结果都不一样,实现了随机发牌。