Java斗地主基础实现笔记
public class Card {
private String color;//花色
private String size;//数字
private int index;//数字大小,方便进行排序
public Card(String color, String size, int index) {
this.color = color;
this.size = size;
this.index = index;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
@Override
public String toString() {
//重写toString方法,方便输出内容而不是地址
return color+size;
}
}
import java.util.*;
public class RunGame {
//创建牌盒
public static List<Card> allCard = new ArrayList<>();
static {
//创建花色盒数字
String[] colors = {"♣", "♠", "♥", "♦"};
String[] sizes = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};
int index = 0;
//组合花色数字,放入牌盒中
for (String size : sizes) {
for (String color : colors) {
Card c = new Card(color, size, index);
allCard.add(c);
index++;
}
}
Card c1 = new Card("", "小王", ++index);
Card c2 = new Card("", "大王", ++index);
Collections.addAll(allCard, c1, c2);
//洗牌
Collections.shuffle(allCard);
}
//发牌
public static void sentCards(List<Card> p1, List<Card> p2, List<Card> p3) {
for (int i = 0; i < allCard.size() - 3; i++) {
Card c = allCard.get(i);
if (i % 3 == 0) {
p1.add(c);
} else if (i % 3 == 1) {
p2.add(c);
} else {
p3.add(c);
}
}
}
//对拿到手上的牌进行从大到小排序
public static void sortCards(List<Card>cards) {
cards.sort((o1, o2) -> o2.getIndex() - o1.getIndex());
}
public static void main(String[] args) {
System.out.println("洗牌前:" + allCard);
Collections.shuffle(allCard);
System.out.println("洗牌后" + allCard);
//创建三个人(集合)接收牌
List<Card> p1 = new ArrayList<>();
List<Card> p2 = new ArrayList<>();
List<Card> p3 = new ArrayList<>();
sentCards(p1, p2, p3);
//展示三个人(集合)收到的牌
System.out.println("p1:" + p1);
System.out.println("p2:" + p2);
System.out.println("p3:" + p3);
//从牌集合中截取底牌,展示底牌
List<Card> lestThreeCards = allCard.subList(allCard.size() - 3, allCard.size());
System.out.println("底牌为:" + lestThreeCards);
//对牌进行排序,展示
sortCards(p1);
sortCards(p2);
sortCards(p3);
System.out.println("排序后");
System.out.println("p1:" + p1);
System.out.println("p2:" + p2);
System.out.println("p3:" + p3);
}
}