-
需求:在启动游戏房间的时候,应该提前准备好54张牌,完成洗牌、发牌、牌排序、逻辑。
-
分析:
-
当系统启动的同时需要准备好数据的时候,就可以用静态代码块了。
-
洗牌就是打乱牌的顺序。
-
定义三个玩家、依次发出51张牌
-
给玩家的牌进行排序(拓展)
-
输出每个玩家的牌数据。
源码如下
package set;
import java.util.*;
public class GameDemo {
public static List<Card> allCards = new ArrayList<>();
static {
String[] sizes = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};
String[] colors = {"♥", "♣", "♦", "♠"};
int index = 0;
for (String size : sizes) {
index++;
for (String color : colors) {
Card c = new Card(size, color, index);
allCards.add(c);
}
}
Card c1 = new Card("", "小王", ++index);
Card c2 = new Card("", "大王", ++index);
Collections.addAll(allCards, c1, c2);
System.out.println("新牌" + allCards);
}
public static void main(String[] args) {
Collections.shuffle(allCards);
System.out.println("洗牌后" + allCards);
List<Card> hui = new ArrayList<>();
List<Card> wen = new ArrayList<>();
List<Card> li = new ArrayList<>();
for (int i = 0; i < allCards.size() - 3; i++) {
Card c = allCards.get(i);
if (i % 3 == 0) {
li.add(c);
} else if (i % 3 == 1) {
liwen.add(c);
} else if (i % 3 == 2) {
liwenhui.add(c);
}
}
List<Card> lastThereCards = allCards.subList(allCards.size() - 3, allCards.size());
sortCards(li);
sortCards(wen);
sortCards(hui);
System.out.println("李: " + li);
System.out.println("文: " + wen);
System.out.println("汇: " + hui);
System.out.println("底牌: " + lastThereCards);
}
private static void sortCards(List<Card> cards) {
Collections.sort(cards, new Comparator<Card>() {
@Override
public int compare(Card o1, Card o2) {
return o1.getIndex() - o2.getIndex();
}
});
}
}
package set;
public class Card {
private String size;
private String color;
private int index;
public Card() {
}
public Card(String size, String color, int index) {
this.size = size;
this.color = color;
this.index = index;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Card(String color) {
this.color = color;
}
@Override
public String toString() {
return size + color;
}
}