实现思路:第一步准备牌、第二步洗牌、第三步发牌、第四步看牌。
程序实现和相关细节如下:
package com.company;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
/*
斗地主案例
*/
public class Main {
//程序的主入口
public static void main(String[] args) {
//1、准备牌
//1.1 定义一个HashMap存储牌
HashMap<Integer,String> poker = new HashMap<>();
//1.2 定义一个ArrayList存储牌的下标
ArrayList<Integer> cardIndex = new ArrayList<>();
//存储大王小王
poker.put(0,"大王");
cardIndex.add(0);
poker.put(1,"小王");
cardIndex.add(1);
//1.2 定义两个数组分别存储花色和数字
String[] colors = {"♠","♥","♣","♦"};
String[] numbers = {"A","K","Q","J","10","9","8","7","6","5","4","3","2"};
int index = 2;
//遍历两个数组,拼装牌
for (String color : colors) {
for (String number : numbers){
poker.put(index,color + number);
cardIndex.add(index);
index++;
}
}
//2、洗牌
Collections.shuffle(cardIndex);
//3、发牌
ArrayList<Integer> diPai = new ArrayList<>();
ArrayList<Integer> player1 = new ArrayList<>();
ArrayList<Integer> player2 = new ArrayList<>();
ArrayList<Integer> player3 = new ArrayList<>();
for (int i = 0; i < cardIndex.size(); i++) {
Integer arrValue = cardIndex.get(i);
if (i > 50){
//给底牌发牌
diPai.add(arrValue);
}else if (i % 3 == 0){
//给玩家一发牌
player1.add(arrValue);
}else if (i % 3 == 1){
//给玩家二发牌
player2.add(arrValue);
}else if (i % 3 == 2){
//给玩家三发牌
player3.add(arrValue);
}
}
//排序
Collections.sort(diPai);
Collections.sort(player1);
Collections.sort(player2);
Collections.sort(player3);
//4、看牌
showHand("底牌",diPai,poker);
showHand("玩家一",player1,poker);
showHand("玩家二",player2,poker);
showHand("玩家三",player3,poker);
}
/*
看牌方法
*/
public static void showHand(String name,ArrayList<Integer> card,HashMap<Integer,String> poker){
ArrayList<String> handCard = new ArrayList<>();
for (int i = 0; i < card.size(); i++) {
Integer value = card.get(i);
String cardValue = poker.get(value);
handCard.add(cardValue);
}
System.out.println(name + "的牌为:" + handCard);
}
}
程序运行结果: