[java]
package net.eudu.jframetest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
[/java]
[java]
public class CardGame2 {
// 存放未解析的0-51整数值,后面会洗牌1000次扰乱,在发牌解析
private List<Integer> nums;
private List<Card>[] players; // 4个玩家
// 弄出0-51整数
public void createNums() {
nums = new ArrayList<Integer>();
for (int i = 0; i < 52; i++) {
nums.add(i);
}
}
<!--more-->
// 来了4个玩家
public void createPlayers() {
players = new List[4];
}
// 洗牌,扰乱nums集合中元素位置
public void ruffle() {
Random random = new Random();
int tmp = 0; // 交换中间量
int randm = 0;
for (int i = 0; i < 1000; i++) {
randm = random.nextInt(52);
tmp = nums.get(randm);
nums.set(randm, nums.get(0));
nums.set(0, tmp);
}
}
public char parserColor(int num) {
char c = '0';
switch (num / 13) {
case 0:
c = '♣';
break;
case 1:
c = '♦';
break;
case 2:
c = '♥';
break;
case 3:
c = '♠';
}
return c;
}
public String parserValue(int num) {
String str = "";
switch (num % 13) {
case 0:
str = "A";
break;
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
str = ((num % 13) + 1) + "";
break;
case 10:
str = "J";
break;
case 11:
str = "Q";
break;
case 12:
str = "K";
}
return str;
}
// 发牌
public void deal() {
for (int i = 0; i < players.length; i++) {
players[i] = new ArrayList<Card>();
}
int i = 0;
while (nums.size() > 0) {
int num = nums.remove(0);
players[i++].add(new Card(parserValue(num), parserColor(num)));
if (i > 3)
i = 0;
}
}
// 排序
public void sortPlayersCards() {
for (List<Card> cards: players) {
Collections.sort(cards);
}
}
public void showEveryOneCards() {
for (List<Card> cards: players) {
for (Card card: cards) {
System.out.print(card.getColor() + " " + card.getValue() + "\t");
}
System.out.println();
}
}
public static void main(String[] args) {
CardGame2 game = new CardGame2();
game.createNums();
game.createPlayers();
game.ruffle();
game.deal();
game.sortPlayersCards();
game.showEveryOneCards();
}
}
class Card implements Comparable<Card>{
private String value; // 牌面值
private char color; // 花色
public Card() {
}
public Card(String value, char color) {
this.value = value;
this.color = color;
}
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setColor(char color) {
this.color = color;
}
public char getColor() {
return color;
}
public int parserValue(String value) {
try {
int num = Integer.parseInt(value) - 2;
if (num == 0)
return 13;
return num;
} catch (NumberFormatException e) {
switch (value) {
case "J":
return 9;
case "Q":
return 10;
case "K":
return 11;
case "A":
return 12;
}
}
return 0;
}
@Override
public int compareTo(Card o) {
return parserValue(value) - parserValue(o.value);
}
}
/*
♠ 3 ♠ 6 ♦ 6 ♥ 7 ♦ 7 ♣ 8 ♥ 9 ♥ 10 ♠ 10 ♥ K ♠ A ♦ A ♣ 2
♦ 5 ♣ 6 ♠ 8 ♠ 9 ♣ 9 ♥ J ♦ Q ♥ Q ♠ K ♥ A ♣ A ♦ 2 ♥ 2
♥ 3 ♣ 4 ♥ 4 ♠ 5 ♥ 6 ♣ 7 ♥ 8 ♦ 8 ♦ 9 ♦ 10 ♣ 10 ♠ J ♣ K
♣ 3 ♦ 3 ♠ 4 ♦ 4 ♣ 5 ♥ 5 ♠ 7 ♣ J ♦ J ♣ Q ♠ Q ♦ K ♠ 2
*/
[/java]