Java实现扑克牌洗牌和发牌

本文实例为大家分享了Java实现扑克牌洗牌发牌的具体代码,供大家参考,具体内容如下

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

下面是实现代码:

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

public class Card {
  private static ArrayList 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 A = new ArrayList<>(); //小人A
  private static ArrayList B = new ArrayList<>(); //小人B
  private static ArrayList C = new ArrayList<>(); //小人C
  private static ArrayList 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");
  }
}

下面是运行结果

Java实现扑克牌洗牌和发牌_第1张图片

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(Java实现扑克牌洗牌和发牌)