Detailed explanation of java_ collection comprehensive case: landlord fighting

  • 2021-07-16 02:22:20
  • OfStack

Case introduction

According to the rules of fighting landlords, complete the action of shuffling and dealing cards. Specific rules: Use 54 cards to disrupt the order, 3 players participate in the game, 3 people touch cards alternately, each person has 17 cards, and the last 3 cards are reserved as cards.

Case analysis

1. Prepare cards:

Cards can be designed as 1 ArrayList, and each string is 1 card. Each card is composed of two parts: color and number. We can use the nested iteration of color set and number set to complete the assembly of each card. Cards are randomly ordered by shuffle method of Collections class.

2. Licensing

Each person and cards are designed as ArrayList, and the last 3 cards are directly stored in the cards, and the remaining cards are dealt in turn by taking the mold of 3 cards.

3. Look at the cards

Print each collection directly.

Code implementation


import java.util.ArrayList;
import java.util.Collections;
public class Poker {
public static void main(String[] args) {
/*
* 1: 准备牌操作
*/
//1.1 创建牌盒 将来存储牌面的
ArrayList<String> pokerBox = new ArrayList<String>();
//1.2 创建花色集合
ArrayList<String> colors = new ArrayList<String>();
//1.3 创建数字集合
ArrayList<String> numbers = new ArrayList<String>();
//1.4 分别给花色 以及 数字集合添加元素
colors.add("♥");
colors.add("♦");
colors.add("♠");
colors.add("♣");
for(int i = 2;i<=10;i++){
numbers.add(i+"");
}
numbers.add("J");
numbers.add("Q");
numbers.add("K");
numbers.add("A");
//1.5 创造牌 拼接牌操作
// 拿出每1个花色 然后跟每1个数字 进行结合 存储到牌盒中
for (String color : colors) {
//color每1个花色 guilian
//遍历数字集合
for(String number : numbers){
//结合
String card = color+number;
//存储到牌盒中
pokerBox.add(card);
}
}
//1.6大王小王
pokerBox.add("小☺");
pokerBox.add("大☠");
// System.out.println(pokerBox);
//洗牌 是不是就是将 牌盒中 牌的索引打乱
// Collections类 工具类 都是 静态方法
// shuffer方法
/*
* static void shuffle(List<?> list)
* 使用默认随机源对指定列表进行置换。
*/
//2:洗牌
Collections.shuffle(pokerBox);
//3 发牌
//3.1 创建 3个 玩家集合 创建1个底牌集合
ArrayList<String> player1 = new ArrayList<String>();
ArrayList<String> player2 = new ArrayList<String>();
ArrayList<String> player3 = new ArrayList<String>();
ArrayList<String> dipai = new ArrayList<String>();
//遍历 牌盒 必须知道索引
for(int i = 0;i<pokerBox.size();i++){
//获取 牌面
String card = pokerBox.get(i);
//留出3张底牌 存到 底牌集合中
if(i>=51){//存到底牌集合中
dipai.add(card);
} else {
//玩家1 %3 ==0
if(i%3==0){
player1.add(card);
}else if(i%3==1){//玩家2
player2.add(card);
}else{//玩家3
player3.add(card);
}
}
}
//看看
System.out.println("令狐冲:"+player1);
System.out.println("田伯光:"+player2);
System.out.println("绿竹翁:"+player3);
System.out.println("底牌:"+dipai);
}
}
 

Related articles: