您的位置:首页 > 编程语言 > Java开发

Java学习笔记34(集合框架八:综合案例:模拟斗地主的洗牌发牌)

2018-01-14 14:50 525 查看
规则:

1.54张扑克牌,有花色

2.顺序打乱,一人一张依次发牌,一人17张,留三张作为底牌

3.看牌:按大小王2A....43的序排列打印

示例:

package demo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

public class DouDiZhu {
public static void main(String[] args) {
// 创建Map集合,键是编号,值是牌
HashMap<Integer, String> pooker = new HashMap<Integer, String>();
// List集合存储编号
// 用List集合原因:可以调用排序方法
ArrayList<Integer> pookerNumber = new ArrayList<Integer>();
// 由于13个点数恒定,定义数组
String[] numbers = { "2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3" };
// 花色恒定,定义数组
String[] colors = { "♠", "♥", "♣", "♦" };
// 定义整数变量,作为键,0和1留给大小王
int index = 2;
// 遍历数组,存入Map集合
for (String number : numbers) {
for (String color : colors) {
pooker.put(index, color + number);
pookerNumber.add(index);
index++;
}
}
// 单独存储大小王
pooker.put(0, "大王");
pookerNumber.add(0);
pooker.put(1, "小王");
pookerNumber.add(1);

// 洗牌,将牌的编号打乱
Collections.shuffle(pookerNumber);

// 发牌
// 三个玩家和底牌
ArrayList<Integer> player1 = new ArrayList<Integer>();
ArrayList<Integer> player2 = new ArrayList<Integer>();
ArrayList<Integer> player3 = new ArrayList<Integer>();
ArrayList<Integer> dipai = new ArrayList<Integer>();
// 每张依次发到三个玩家
for (int i = 0; i < pookerNumber.size(); i++) {
// 先将底牌做好
if (i < 3) {
dipai.add(pookerNumber.get(i));
}
// 依次给每个玩家发牌
else if (i % 3 == 0) {
player1.add(pookerNumber.get(i));
} else if (i % 3 == 1) {
player2.add(pookerNumber.get(i));
} else if (i % 3 == 2) {
player3.add(pookerNumber.get(i));
}
}
// 对玩家手中的牌排序
Collections.sort(player1);
Collections.sort(player2);
Collections.sort(player3);
// 看牌,根据键找值
look("玩家1", player1, pooker);
look("玩家2", player2, pooker);
look("玩家3", player3, pooker);
look("底牌", dipai, pooker);
}

public static void look(String name, ArrayList<Integer> player, HashMap<Integer, String> pooker) {
System.out.print(name + ":");
for (Integer key : player) {
String value = pooker.get(key);
System.out.print("    " + value);
}
System.out.println();
}
}


效果:



每次的结果都不一致:



有兴趣的朋友可以根据斗地主的规则继续开发下去,做成一个简易的斗地主游戏
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: