这是核心算法
package com.veechin.java.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import com.veechin.java.util.Card;
public class test {
public static void main(String arg[]){
Card cards[]=new Card[52];
String type[]={"红桃","黑桃","方片","梅花"};
//初始化牌类
for(int i=0;i<4;i++)
for(int j=0;j<13;j++){
cards[i*13+j]=new Card(j+1,type[i]);
}
//转变成集合
ArrayList<Card> cardset=new ArrayList<Card>(Arrays.asList(cards));
//洗牌
Collections.shuffle(cardset);
//发牌
List<Card> player_one= cardset.subList(0, 13);
List<Card> player_two= cardset.subList(13, 26);
List<Card> player_three= cardset.subList(26, 39);
List<Card> player_four= cardset.subList(39, 52);
System.out.println("Player_One的牌");
//排牌
SortedSet<Card> player_one_sorted=new TreeSet<Card>(new Comparator<Card>() {
public int compare(Card c1, Card c2) {
return c1.compareTo(c2);
}
});
player_one_sorted.addAll(player_one);
for(Card temp:player_one_sorted){
temp.getCardInfor();
}
System.out.println("Player_Two的牌");
//排牌
SortedSet<Card> player_two_sorted=new TreeSet<Card>(new Comparator<Card>() {
public int compare(Card c1, Card c2) {
return c1.compareTo(c2);
}
});
player_two_sorted.addAll(player_two);
for(Card temp:player_two_sorted){
temp.getCardInfor();
}
System.out.println("Player_Three的牌");
//排牌
SortedSet<Card> player_three_sorted=new TreeSet<Card>(new Comparator<Card>() {
public int compare(Card c1, Card c2) {
return c1.compareTo(c2);
}
});
player_three_sorted.addAll(player_three);
for(Card temp:player_three_sorted){
temp.getCardInfor();
}
System.out.println("Player_Four的牌");
//排牌
SortedSet<Card> player_four_sorted=new TreeSet<Card>(new Comparator<Card>() {
public int compare(Card c1, Card c2) {
return c1.compareTo(c2);
}
});
player_four_sorted.addAll(player_four);
for(Card temp:player_four_sorted){
temp.getCardInfor();
}
}
}
下面是牌类:
package com.veechin.java.util;
public class Card implements Comparable<Card>{
private int Size;
private String Type;
public Card(int size,String type){
this.Size=size;
this.Type=type;
}
public void getCardInfor(){
System.out.println("Size: "+Size+" Type: "+Type);
}
public int compareTo(Card other) {
if(this.Size-other.Size==0){
return 1;
}
return this.Size-other.Size;
}
}
//运行结果如下:
当然如果想作游戏的话还须要修改添加进去大小王.