一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

java使用HashMap实现斗地主代码示例

时间:2021-03-02 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下java使用HashMap实现斗地主代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

案例介绍

按照斗地主的规则,完成洗牌发牌的动作。 具体规则:

使用54张牌打乱顺序,三个玩家参与游戏,三人交替摸牌,每人17张牌,最后三张留作底牌。

案例分析

1、准备牌:

每张扑克牌牌由花色和数字两部分组成。可以使用花色集合与数字集合嵌套迭代完成扑克牌的组装。

2、发牌

扑克牌组转完毕后由Collections类的shuffle方法打乱重排,最后3张当作底牌,剩余牌通过对3取模依次发牌。

3、看牌

打印集合。

代码演示

import java.util.*;

/**
 * @author layman
 */
public class Poker2 {
 // 牌堆
 private static Map pokerMap = new HashMap<>();
 // 花色
 private static ArrayList colors = new ArrayList<>();
 // 数字
 private static ArrayList numbers = new ArrayList<>();
 // 扑克牌的编号集合
 private static ArrayList numberList = new ArrayList<>();
 // 玩家编号集合
 private static ArrayList noP1 = new ArrayList<>();
 private static ArrayList noP2 = new ArrayList<>();
 private static ArrayList noP3 = new ArrayList<>();
 // 底牌编号集合
 private static ArrayList diPaiNo = new ArrayList<>();

 // 三个玩家
 private static ArrayList playerOne = new ArrayList();
 private static ArrayList playerTwo = new ArrayList();
 private static ArrayList playerThree = new ArrayList();
 // 底牌
 private static ArrayList diPai = new ArrayList();
 /**
  * 创建扑克牌并洗牌
  */
 public static void createPoker(){
  
  Collections.addAll(colors, "♦", "♣", "♥", "♠");
  Collections.addAll(numbers, "2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3");
  // 设置存储编号
  int count = 1;
  pokerMap.put(count++, "大王");
  pokerMap.put(count++, "小王");
  // 创建扑克牌
  for (String number : numbers) {
   for (String color : colors) {
    String card = color + number;
    pokerMap.put(count++, card);
   }
  }
  
  // 先取编号
  Set numberSet = pokerMap.keySet();
  numberList.addAll(numberSet);

  // 然后随机洗牌
  Collections.shuffle(numberList);
 }

 /**
  * 发牌
  */
 public static void faPai(){
  for (int i = 0; i < numberList.size(); i++) {
   Integer no = numberList.get(i);
   // 留出底牌
   if (i >= 51) {
    diPaiNo.add(no);
   } else {
    if (i % 3 == 0) {
     noP1.add(no);
    } else if (i % 3 == 1) {
     noP2.add(no);
    } else {
     noP3.add(no);
    }
   }
  }
 }
 /**
  * 发牌并排序
  */
 public static void sortCards(){
  // 对编号进行排序
  Collections.sort(noP1);
  Collections.sort(noP2);
  Collections.sort(noP3);
  Collections.sort(diPaiNo);
  // 进行牌面的转换
  for (Integer i : noP1) {
   // 根据编号获取牌面,并发给对应的玩家
   String card = pokerMap.get(i);
   playerOne.add(card);
  }
  for (Integer i : noP2) {
   String card = pokerMap.get(i);
   playerTwo.add(card);
  }
  for (Integer i : noP3) {
   String card = pokerMap.get(i);
   playerThree.add(card);
  }
  for (Integer i : diPaiNo) {
   String card = pokerMap.get(i);
   diPai.add(card);
  }
 }
 /**
  * 看牌
  */
 public static void showCards(){
  System.out.println("赌圣:" + playerOne);
  System.out.println("赌侠:" + playerTwo);
  System.out.println("赌王:" + playerThree);
  System.out.println("底牌:" + diPai);
 }
 public static void main(String[] args) {
  createPoker();
  faPai();
  sortCards();
  showCards();
 }
}

热门栏目