亲宝软件园·资讯

展开

java扑克牌洗牌和发牌 Java实现扑克牌洗牌和发牌

feng海涛 人气:0

实现原理:使用4种花色和13个数字组合成52张牌,放进一个集合中;通过把集合数据排序打乱实现洗牌操作,然后在通过循环把牌抽出来实现发牌操作。

下面是实现代码:

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

public class Card {
  private static ArrayList<String> list = new ArrayList<>();
  private static String[] colors = {"黑桃","红桃","梅花","方块"};
  private static String[] nums = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
  private static String[] jokers = {"Joker","joker"}; //大小王
  private static ArrayList<String> A = new ArrayList<>(); //小人A
  private static ArrayList<String> B = new ArrayList<>(); //小人B
  private static ArrayList<String> C = new ArrayList<>(); //小人C
  private static ArrayList<String> D = new ArrayList<>(); //小人D

  //初始化扑克牌
  public static void initCards(boolean need){
    for(String color:colors){
      for (String num:nums) {
        list.add(color + num);
      }
    }
    //是否添加大小王
    if (need) {
      list.add(jokers[0]);
      list.add(jokers[1]);
    }
  }

  //洗牌
  public static void xiPai(){
    Collections.shuffle(list);
  }

  //性感荷官,在线发牌
  public static void faPai(){
    A.clear();
    B.clear();
    C.clear();
    D.clear();
    for (int i = 0; i < list.size();i++) {
      if (i%4 == 0) {
        A.add(list.get(i));
      }
      if (i%4 == 1) {
        B.add(list.get(i));
      }
      if (i%4 == 2) {
        C.add(list.get(i));
      }
      if (i%4 == 3) {
        D.add(list.get(i));
      }
    }
  }

  //主方法
  public static void main(String args[]){
    initCards(true);
    xiPai();
    faPai();
    System.out.print("小人A" + A + "\n");
    System.out.print("小人B" + B + "\n");
    System.out.print("小人C" + C + "\n");
    System.out.print("小人D" + D + "\n");
  }
}

下面是运行结果

加载全部内容

相关教程
猜你喜欢
用户评论