如何在Android上随机播放ArrayMap

时间:2019-04-16 10:51:51

标签: java android

我正在生成一个ArrayMap来玩纸牌游戏,我想对arrayMap进行改组,以便我可以顺次选择而不会出现问题,有一些方法可以帮助我,例如Arraylists中存在的.shuffle()。

public ArrayMap<Integer,Carta> carte=new ArrayMap<>(dimensioneMazzo); 

for(int i=0;i<4;i++){
    for(int j=1;j<=10;j++){
        switch(i){
            case 0: 
                carte.put(cartePresenti,new Carta(j,Semi.Denari,false,false));
                break;
            case 1: 
                carte.put(cartePresenti,new Carta(j,Semi.Bastoni,false,false));
                break;
            case 2: 
                carte.put(cartePresenti,new Carta(j,Semi.Coppe,false,false));
                break;
            case 3: 
                carte.put(cartePresenti,new Carta(j,Semi.Spade,false,false));
                break;
            }

            this.cartePresenti=cartePresenti+1;
        }
    }

如果没有一种方法,我该如何随机生成卡?

2 个答案:

答案 0 :(得分:1)

假设cartePresenti从零开始。这应该起作用:

Random r = new Random();

int n = carte.size();
for (int i = n - 1; i > 0; i--) {  
    int j = r.nextInt(i + 1); 

    Carta temp = carte.get(i); 
    carte.put(i, carte.get(j));
    carte.put(j, temp);
} 

答案 1 :(得分:0)

使用Collection.shuffle()的替代解决方案:

//List of the indexes of the card in the old map
List<Integer> indexes = new ArrayList<Integer>();
//Map shuffled
Map<Integer, Carta> shuffledCarte = new ArrayMap<Integer, Carta>();

//Collect the indexes
For(int i = 0; i<carte.size(); i++) {
    indexes.add(i);
}

//Shuffle the indexes
indexes.shuffle();

//Create the new map, using the shuffled indexes
for(int j = 0; j<carte.size(); j++) {
    shuffledCarte.put(j, carte.get(idexes.get(j)));
}