Stack "mischen"
-
Hallo.
Ich will ein Kartenspiel programmieren. Den Kartenstapel habe ich als Stack implementiert. ICh will die Karten aber vorher mischen. Ist es möglich Elemente eines Stacks zu tauschen. Ich habe mir vorher ein Array gebuat wo ich die ELmente tuasche und dann dsa fertige Array in den Stack schiebe.
HIer meine Lösung :// create a new stack for the cards this.deckCards = new Stack<BlackJackCard>(); // set the size of the vector this.deckCards.setSize(CardsInDeck * BlackJackApplication.blackJackDeckSize); // add the cards to the temp deck BlackJackCard tmpDeck[] = new BlackJackCard[ CardsInDeck * BlackJackApplication.blackJackDeckSize ]; int index = 0; for (int cardColor = 0; cardColor < BlackJackCardColor.values().length; cardColor++){ for (int cardType = 0; cardType < BlackJackCardType.values().length; cardType++){ tmpDeck[ index ] = new BlackJackCard(BlackJackCardColor.values()[ cardColor ], BlackJackCardType.values()[ cardType ]); index++; } } // shuffle the stack Random rnd = new Random(); for (index = 0; index < tmpDeck.length; index++){ BlackJackCard tmpCard = tmpDeck[ index ]; int tmpNumber = rnd.nextInt(tmpDeck.length); tmpDeck[ index ] = tmpDeck[ tmpNumber ]; tmpDeck[ tmpNumber ] = tmpCard; } // add the cards to the deck for (index = 0; index < tmpDeck.length; index++){ this.deckCards.push(tmpDeck[ index ]); }
Hat jemand noch eine bessere Idee ?
VIelen Dank
-
Die Collections-API ist dein Freund,
Collections.shuffle()
die Lösung.http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle(java.util.List)
-