1.模拟斗地主
- 需求:通过程序实现斗地主过程中的洗牌,发牌和看牌
- 思路:
①创建一个牌盒,定义一 个集合对象,用ArrayList集合实现
②往牌盒里面装牌
③洗牌,把牌打撒,用Collections的shuffle()方法实现
④发牌,遍历集合,给三个玩家发牌
⑤看牌,三个玩家分别遍历自己的牌
public class Doudizhu {
public static void main(String[] args) {
ArrayList<String> array = new ArrayList<>();
String[] colors = { "♥", "♣", "♦", "♠" };
String[] numbers = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" };
for (String col : colors) {
for (String num : numbers) {
array.add(col + num);
}
}
array.add("RJoker");
array.add("BJoker");
Collections.shuffle(array);
ArrayList<String> player1 = new ArrayList<>();
ArrayList<String> player2 = new ArrayList<>();
ArrayList<String> player3 = new ArrayList<>();
ArrayList<String> dipai = new ArrayList<>();
for (int i = 0; i < array.size(); i++) {
String poker = array.get(i);
if (i >= array.size() - 3) {
dipai.add(poker);
} else if (i % 3 == 0) {
player1.add(poker);
} else if (i % 3 == 1) {
player2.add(poker);
} else if (i % 3 == 2) {
player3.add(poker);
}
}
look("玩家1", player1);
look("玩家2", player2);
look("玩家3", player3);
look("底牌", dipai);
}
public static void look(String player, ArrayList<String> arr) {
System.out.print(player + "的牌是:");
for (String s : arr) {
System.out.print(s + " ");
}
System.out.println();
}
}
2.模拟斗地主升级版
- 需求:通过程序实现斗地主过程中的洗牌,发牌和看牌。
- 要求:对牌进行排序
- 思路:
①创建HashMap,键是编号,值是牌
②创建ArrayList, 存储编号
③创建花色数组和点数数组
④从开始往HashMap里面存储编号,并存储对应的牌。同时往ArrayList里面存储编号
⑤洗牌(洗的是编号),用Collections的shuffle()方法实现
⑥发牌(发的也是编号,为了保证编号是排序的,创建TreeSet集合接收)
⑦定义方法看牌(遍历TreeSet集合,获取编号,到HashMap集合找对应的牌)
⑧调用看牌方法
public class NewDoudizhu {
public static void main(String[] args) {
HashMap<Integer, String> hs = new HashMap<>();
ArrayList<Integer> array = new ArrayList<>();
String[] colors = { "♥", "♣", "♦", "♠" };
String[] numbers = { "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2" };
int index = 0;
for (String num : numbers) {
for (String col : colors) {
hs.put(index, col + num);
array.add(index);
index++;
}
}
hs.put(index, "BJoker");
array.add(index);
index++;
hs.put(index, "RJoker");
array.add(index);
Collections.shuffle(array);
TreeSet<Integer> player1 = new TreeSet();
TreeSet<Integer> player2 = new TreeSet();
TreeSet<Integer> player3 = new TreeSet();
TreeSet<Integer> dipai = new TreeSet();
for (int i = 0; i < array.size(); i++) {
Integer Jnum = array.get(i);
if (i >= array.size() - 3) {
dipai.add(Jnum);
} else if (i % 3 == 0) {
player1.add(Jnum);
} else if (i % 3 == 1) {
player2.add(Jnum);
} else if (i % 3 == 2) {
player3.add(Jnum);
}
}
look("玩家1", player1, hs);
look("玩家2", player2, hs);
look("玩家3", player3, hs);
look("底牌", dipai, hs);
}
public static void look(String name, TreeSet<Integer> ts, HashMap<Integer, String> hs) {
System.out.print(name + "的牌是:");
for (Integer key : ts) {
String poker = hs.get(key);
System.out.print(poker + " ");
}
System.out.println();
}
}