用数组和集合实现斗地主案例
一、准备54张牌,存储到一个集合中
2张特殊牌:大王,小王
其他52张牌,定义两个数组
数组一:储存5个花色♠,♥,♣,♦
数组二:储存13个序号(由大到小)2,A,K,Q…5,4,3
import java.util.ArrayList;
public class Doudizhu {
public static void main(String[] args) {
// 一、准备牌
String [] colors = {"♠","♥","♣","♦"}; //定义两个数组,一个储存花色,一个储存序号
String [] numbers = {"2 ","A ","K ","Q ","J ","10 "," 9"," 8","7 "," 6"," 5"," 4","3 ",};
ArrayList<String> poker = new ArrayList(); // 定义一个能存储54张牌的ArrarList集合,泛型使用String
poker.add("大王"); // 先把两张特殊牌(大王,小王)存进集合。
poker.add("小王");
// 用加强for循环遍历两个数组,组装52张牌
for (String number:numbers){
for (String color:colors){
poker.add(number+color); //把组装好的牌存进集合
}
}
System.out.println(poker); //打印出54张牌
}
}
二、洗牌
使用集合的工具类collections中的shuffle方法将组装好的54张牌打乱顺序
1,先导入Collections工具类
import java.util.Collections;
2,使用shuffle方法
Collections.shuffle(poker); //使用shuffle()打乱集合中的元素顺序
三、发牌
定义四个集合,存储发给三个玩家的牌和三张底牌
ArrayList<String> Play1 = new ArrayList<>(); //存储玩家一的牌
ArrayList<String> Play2 = new ArrayList<>(); //存储玩家二的牌
ArrayList<String> Play3 = new ArrayList<>(); //存储玩家三的牌
ArrayList<String> dipai = new ArrayList<>(); //存储3张底牌
遍历poker集合,获取每一张牌,使用poker集合的索引%3给三个玩家轮流发牌
剩余三张牌给底牌
注意:先判断底牌索引值(i>=51),否则牌发没了
for (int i = 0; i <= 53; i++) {
String p = poker.get(i); //获取每一张牌
if (i >= 51){
dipai.add(p); //发底牌
}else if (i%3 == 0){
Play1.add(p); //给玩家一发牌
}else if(i%3 == 1){
Play2.add(p); //给玩家二发牌
}else if (i%3 == 2){
Play3.add(p); //给玩家三发牌
}
}
四、看牌
打印出三个玩家的牌和底牌
System.out.println(Play1);
System.out.println(Play2);
System.out.println(Play3);
System.out.println(dipai);
五、运行结果
周润发:[ 5♦, 3 ♥, A ♥, 7 ♠, 3 ♦, J ♣, 8♥, 10 ♦, 7 ♣, 6♠, 10 ♥, 9♥, J ♦, 6♣, 4♣, 2 ♠, 3 ♠]
刘德华:[Q ♥, 7 ♥, 大王, 8♦, 2 ♦, 5♥, 9♣, J ♠, 8♣, K ♣, J ♥, 9♦, K ♠, 10 ♣, Q ♣, 6♦, 4♠]
周星驰:[小王, A ♦, 7 ♦, 4♥, K ♦, 4♦, 3 ♣, 8♠, 5♠, A ♠, 10 ♠, Q ♠, Q ♦, 2 ♣, 6♥, 5♣, K ♥]
底牌:[ 9♠, A ♣, 2 ♥]