对于这个的讲解,代码注释写了
public class Poker { private String suit;//牌的花色 private int rank;//牌的数字 public Poker(String suit, int rank) { this.suit = suit; this.rank = rank; } @Override public String toString() {//一定不要忘记重写toString方法 return "{" +suit+" "+rank+"}"; } public String getSuit() { return suit; } public void setSuit(String suit) { this.suit = suit; } public int getRank() { return rank; } public void setRank(int rank) { this.rank = rank; } }
import java.util.*; /** * Created with IntelliJ IDEA. * Description: * User: WHY * Date: 2022-12-02 * Time: 15:44 */ public class Game { public String[] suits = {"♥", "♣", "♦", "♠"}; //现在没有牌,我们得买牌,写一个买牌方法 public List<Poker> buyPokers() { List<Poker> pokers = new ArrayList<>(); for (int i = 0; i < 4; i++) { for (int j = 1; j <= 13; j++) { Poker poker = new Poker(suits[i], j); pokers.add(poker); } } return pokers; } //现在有牌了,我们要进行玩牌了,但是在玩牌前我们还要进行一个操作,那就是打乱操作 //,现在的牌是有序的,我们要让它无序 //所以要使用random操作,打乱牌,如果从前忘记打乱,那么假如是51,那么就是0-50,一次这样就会很麻烦,还会漏牌,如果用从后往前,直接遍历这个数组,从后往前遍历 //进行洗牌操作 // 将i下标扔到random 这个库方法中 public void wash(List<Poker> pokers) { for (int i = pokers.size() - 1; i > 0; i--) { Random random = new Random(); int index = random.nextInt(i); swap(pokers,i,index); } } private void swap(List<Poker> pokers,int i,int j){ Poker tmp=pokers.get(i); pokers.set(i,pokers.get(j));//i pokers.set(j,tmp); } //洗完牌,可以开始玩牌了 public List<List<Poker>> play( List<Poker> pokers) { List<List<Poker>> hand = new ArrayList<>(); //玩牌规则是这样的,三个人每个人轮流抓五次牌 //那么这就是一个二维数组,所以得继续new ArrayList List<Poker> hand1 = new ArrayList<>(); List<Poker> hand2 = new ArrayList<>(); List<Poker> hand3 = 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++) { //揭牌就相当于删除数组的0下标,删的这个元素放到hand中,调用remove方法进行删除 Poker removerPoker = pokers.remove(0); hand.get(j).add(removerPoker); } } return hand; } }
mport java.util.List; /** * Created with IntelliJ IDEA. * Description: * User: WHY * Date: 2022-12-02 * Time: 15:53 */ public class Test { public static void main(String[] args) { Game game=new Game(); List<Poker> pokers = game.buyPokers(); System.out.println(pokers); //洗牌 game.wash(pokers); // System.out.println("洗牌:"); System.out.println(pokers); //揭牌 System.out.println("揭牌"); List<List<Poker>>hand= game.play(pokers); for (int i = 0; i < hand.size(); i++) { System.out.println("第 "+(i+1)+"个人的牌:"+hand.get(i)); } System.out.println("剩下的牌:"); System.out.println(pokers); } }
这就是对顺序表的简单应用,重点是二维数组对应的顺序表,以及洗牌函数的实现!!!