java----买牌和洗牌

  1. 问题描述
    实现一个买扑克牌和洗扑克牌的问题
  2. 解决思路
    创建一个类表示一张牌, 然后将牌放入顺序表中.
    根据每张牌在顺序表中的下标, 与随机找的下标的牌进行交换, 实现洗牌.
  3. 源代码
    一张牌
public class Card {
    // 点数
    String rank;
    // 花色
    String suit;

    public Card(String rank, String suit) {
        this.rank = rank;
        this.suit = suit;
    }

    @Override
    public String toString() {
        return "(" + rank + suit + ')';
    }
}

对牌的操作

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class PokerGame {
    public static final String[] suits = {"♣", "♠", "♥", "♦"};
    private static List<Card> burPoker() {
        // 向上转型
        List<Card> poker = new ArrayList<>();
        for (int i= 0; i < 4; i++) {
            for (int j = 2; j <= 10; j++) {
                poker.add(new Card("" +j, suits[i]));
            }
            poker.add(new Card("A", suits[i]));
            poker.add(new Card("J", suits[i]));
            poker.add(new Card("Q", suits[i]));
            poker.add(new Card("K", suits[i]));
        }
        poker.add(new Card("Big Joker", ""));
        poker.add(new Card("Small Joker", ""));
        return poker;
    }

    public static void shuffle(List<Card> poker) {
        Random random = new Random();
        for (int i = poker.size() - 1; i > 0; i--) {
            int pos = random.nextInt(i);
            swap(poker, i, pos);
        }
    }

    private static void swap(List<Card> poker, int i, int pos) {
        Card temp = poker.get(i);
        poker.set(i, poker.get(pos));
        poker.set(pos, temp);
    }

    public static void main(String[] args) {
        List<Card> poker = burPoker();
        System.out.println(poker);
        shuffle(poker);
        System.out.println(poker);
    }
    
}

上一篇:linux 查看显卡驱动


下一篇:3D扭动卡片 html+css+js