1️⃣ initialize topCardIndex to its starting value of 0
#
The topCardIndex keeps track of which card is the current “top card”.
2️⃣ initialize cards with all 52 cards from the deck
#
To create all the cards in a deck, you can use nested for-loops to combine the 4 possible suit (❤️♠️♦️♣️) with the 13 possible ranks (1,2,3,4,5,6,7,8,9,10,11,12,13)
Here is an example of using nested for loops to generate all possible weekday blocks:
String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
int[] blocks = {1, 2, 3, 4, 5};
for (int i = 0; i < days.length; i++) {
for (int j = 0; j < blocks.length; j++) {
System.out.println(days[i]+" block "+ blocks[j]);
}
}
💻 Write a method shuffle() that randomly swaps the card objects inside the cards array
1️⃣ loop through every position cards array 2️⃣ each time you loop, randomly generate another location in the array, rand_i 3️⃣ swap the card located at i with the card located at rand_i
Here’s how to randomly generate a number 0-9:
Random rand =new Random(); // you only need to run this onceint randomIndex = rand.nextInt(10); //each time you need a new random number, run this line of code
Unfortunately, we can’t guarantee that every space in the player’s hand always has a card in it. What if you are playing a game like Uno, where players discard as they go?
For example, imagine you are writing calculateScore:
// Calculate the total score of a hand of cardspublicintcalculateScore(Card[] hand) {
int score = 0;
for (int i = 0; i < hand.length; i++) {
Card card = hand[i];
score += card.getRank();
}
return score;
}
If one of the spaces in hand is null, but you call a method like getRank anyway, you will get something called a NullPointerException. Here are two ways to avoid a NullPointerException:
Add in an if statement to test if the object is null:
#
publicintcalculateScore(Card[] hand) {
int score = 0;
for (int i = 0; i < hand.length; i++) {
if(hand[i]!=null) {
Card card = hand[i];
score += card.getRank();
}
}
return score;
}