dimanche 31 janvier 2021

Select from List of cards (strings) at random, but allow ignoring of previously chosen cards (strings) next time around?

I am trying to make a card game in android studio. I had it working completely fine before, any time I click a "roll" button in android studio it would loop through the list of cards and show them one by one. Only problem was it would repeat the output of cards

I felt making another list of selected cards via their "random" index would be the best way of doing this. However, now my code is very messy and does not handle the logic correctly.

    public String shuffleCards() {

        // Strings to return to the user
        String errorString = "ERROR: NO CARDS IN DECK" + '\n' + '\n' + "Go to 'EDIT CARDS' to add game cards to the current deck.";
        String completedString = "All cards in deck have been shown." + '\n' + '\n' + "Go back to the MAIN MENU to restart";


        List<String> allCards = this.getRandomCards();
        List<Integer> cardsDone = new ArrayList<>();

        int randIndex = new Random().nextInt(allCards.size());


        if (!allCards.isEmpty()) {
            //generate rand int [0, size]
            String randString = allCards.get(randIndex); //get random string
            //check for all cards that have been done.
            if (!cardsDone.contains(randIndex)) {
                cardsDone.add(randIndex);
                return randString;
            } else if (cardsDone.size() == allCards.size()) {
                return completedString;
                }
            else {
            }
            return randString;
        }
        return errorString;
    }
}

Can anyone help fix this code so it handles the logic correctly, as well as give me any tips to make this not as messy (I feel like it can be much simpler).

Thanks :)

Aucun commentaire:

Enregistrer un commentaire