欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

如何轻松实现洗牌和发牌?

最编程 2024-01-26 12:22:42
...
import java.util.ArrayList; import java.util.List; import java.util.Random; public class pokers { public static final String[] SUITS = {"♠","♥","♣","♦"}; //买一副扑克牌 public static List<poker> buypokers() { List<poker> pokerList = new ArrayList<>(); for (int i = 0; i < 4; i++) { for (int j = 1; j <= 13; j++) { pokerList.add(new poker(SUITS[i],j)); } } return pokerList; } //洗牌 public static void shuffle(List<poker> pokerList) { Random random = new Random(); for (int i = pokerList.size()-1; i > 0; i--) { int index = random.nextInt(i); swap(pokerList, i, index); } } //交换 public static void swap (List<poker> pokerList, int i, int index) { poker tmp = pokerList.get(i); pokerList.set(i, pokerList.get(index)); pokerList.set(index, tmp); } public static void main(String[] args) { List<poker> pokerList = buypokers(); System.out.println("新牌:" + pokerList); shuffle(pokerList); System.out.println("洗牌:" + pokerList); //揭牌 3个人 每个人轮流揭5张牌 //用来存放三个人揭起来的牌 List<poker> hand1 = new ArrayList<>(); List<poker> hand2 = new ArrayList<>(); List<poker> hand3 = new ArrayList<>(); List<List<poker>> hand = new ArrayList<>(); hand.add(hand1); hand.add(hand2); hand.add(hand3); for (int i = 0; i < 5; i++) { for (int j = 0; j < 3; j++) { //确定是谁在摸牌 List<poker> tmpHand = hand.get(j); tmpHand.add(pokerList.remove(0)); } } //输出每个人的牌 for (int i = 0; i < hand.size(); i++) { System.out.println("第"+(i+1)+"个人的牌是"+hand.get(i)); } System.out.println("剩余的牌有"+pokerList); } }

推荐阅读