Как я могу выйти из этой функции? - PullRequest
0 голосов
/ 15 апреля 2020

Я создаю java программу, которая имитирует карточную игру "война". Будьте осторожны, я довольно новичок в кодировании. В моей колоде 54 карты, включая двух джокеров. После начала войны моя программа запускает бесконечные войны и продолжает добавлять все больше и больше карт в колоды моих игроков. Кто-нибудь может увидеть, что мне не хватает? Это моя функция воспроизведения:

public void play() {
        roundCount = 1;
        //make sure player decks are not empty
        while (!player1.isEmpty() && !player2.isEmpty()) {
            //lay down top card
            Card p1card = player1.pop();
            Card p2card = player2.pop();
            //report cards played
            System.out.println("Round: " + roundCount + "\n" + "Player One Card: " + p1card + "\n" + "Player Two Card: " + p2card);
            //if player one wins, add both cards to player one deck
            if (p1card.getValue() > p2card.getValue()) {
                player1.addCard(p2card);
                player1.addCard(p1card);
                System.out.println("Player One wins this Round.");
                //check card counts
                System.out.println("Player One new card count: " + player1.size());
                System.out.println("Player Two new card count: " + player2.size() + "\n");
                roundCount++;
            }
            //if player two wins, add both cards to player two deck
            else if (p2card.getValue() > p1card.getValue()) {
                player2.addCard(p1card);
                player2.addCard(p2card);
                System.out.println("Player Two wins this Round.");
                //check card counts
                System.out.println("Player One new card count: " + player1.size());
                System.out.println("Player Two new card count: " + player2.size() + "\n");
                roundCount++;
            }
            //if values are equal, start a war
            else if (p1card.getValue() == p2card.getValue()) {
                System.out.println("Time to declare war!");
                //set up arrays to store cards used in the war
                ArrayList<Card> p1List = new ArrayList<Card>();
                ArrayList<Card> p2List = new ArrayList<Card>();
                //call warRound function
                warRound(player1, player2, p1List, p2List);
                //if player one wins the war, add initial round cards
                if (warRound(player1, player2, p1List, p2List) == player1) {
                    player1.addCard(p1card);
                    player1.addCard(p2card);
                    //check card counts
                    System.out.println("Player One card count: " + player1.size());
                    System.out.println("Player Two card count: " + player2.size());
                }
                //if player two wins the war, add initial round cards
                else if (warRound(player1, player2, p1List, p2List) == player2) {
                    player2.addCard(p1card);
                    player2.addCard(p2card);
                    //check card counts
                    System.out.println("Player One card count: " + player1.size());
                    System.out.println("Player Two card count: " + player2.size());
                }

            }

        }
        //player one runs out of cards
        if (player1.isEmpty()) {
            System.out.println("Player Two has won the game.");
            System.out.println("Player One card count: " + player1.size());
            System.out.println("Player Two card count: " + player2.size());
        }
        //player two runs out of cards
        else if (player2.isEmpty()) {
            System.out.println("Player One has won the game.");
            System.out.println("Player One card count: " + player1.size());
            System.out.println("Player Two card count: " + player2.size());
        }
    }

, а затем это моя функция, которая запускает войны:

public Player warRound(Player player1, Player player2, ArrayList<Card> p1List, ArrayList<Card> p2List) {
        warCount = 1;
        //check that players have enough cards for the war
        if (player1.size()>=4 && player2.size()>=4) {
            //lay down three cards for each player
            for (int i = 0; i < 3; i++) {
                p1List.add(player1.pop());
            }
            for (int i = 0; i < 3; i++) {
                p2List.add(player2.pop());
            }
            //temporary test to make sure for loops add correct amount of cards
            System.out.println("Test: " + p1List.size() + p2List.size());

            //cards used to determine war winner
            Card p1War = player1.pop();
            System.out.println("Player one war card: " + p1War);
            Card p2War = player2.pop();
            System.out.println("Player two war card: " + p2War);

            //war outcomes
            if (p1War.getValue() > p2War.getValue()) {
                //if player one wins, add cards from both arrays to player one deck
                for (Card retrieveCard : p1List) {
                    player1.addCard(retrieveCard);
                }
                for (Card wonCard : p2List) {
                    player1.addCard(wonCard);
                }
                //add cards that determined winner to player one deck
                player1.addCard(p1War);
                player1.addCard(p2War);
                System.out.println("Player One won the war!");
                return player1;
            } else if (p1War.getValue() < p2War.getValue()) {
                //if player two wins, add cards from both arrays to player two deck
                for (Card retrieveCard : p2List) {
                    player2.addCard(retrieveCard);
                }
                for (Card wonCard : p1List) {
                    player2.addCard(wonCard);
                }
                //add cards used to determine war winner to player two deck
                player2.addCard(p2War);
                player2.addCard(p1War);
                System.out.println("Player Two won the war!");
                //check card counts
                return player2;
            } else {
                //if there is a double war, add initial comparison cards to arrayList
                //call for another war round
                System.out.println("A war within a war has begun!");
                p1List.add(p1War);
                p2List.add(p2War);
                //check each player has enough cards for another war
                if (player1.size()>=4 && player2.size()>=4) {
                    warRound(player1, player2, p1List, p2List);
                }
                //if one player does not have enough cards for another war, other player wins
                else if (player1.size()<4 || player2.size()<4) {
                    System.out.println("One of the players does not have enough cards for a war!");
                    if (player1.size() > player2.size()) {
                        System.out.println("Player Two ran out of cards, and Player One is the winner!");
                        return null;
                    } else if (player2.size() > player1.size()) {
                        System.out.println("Player One ran out of cards, and Player Two is the winner!");
                        return null;
                    }
                }
                warCount++;
            }
        }
        //if one player does not have enough cards for war, other player wins
        else if (player1.size()<4 || player2.size()<4) {
            if (player1.size() > player2.size()) {
                System.out.println("Player Two ran out of cards, and Player One is the winner!");
                return player1;
            } else if (player2.size() > player1.size()) {
                System.out.println("Player One ran out of cards, and Player Two is the winner!");
                return player2;
            }
        }
        warCount++;
        throw new IllegalStateException();
    }

У меня также есть функция в этом классе, которая инициализирует колоду, и мой принт Заявления показывают, что он работает правильно. У меня есть отдельные классы, которые создают карты, начальную колоду и моих игроков. Если было бы полезно показать эти классы, я могу опубликовать обновление с большим количеством кода. Заранее спасибо.

(отредактировано для добавления класса моего игрока)

package midterm_proj;

import java.util.ArrayDeque;

public class Player {
    //instance variables
    private ArrayDeque<Card> playerdeck;
    //constructor
    public Player() {
        playerdeck = new ArrayDeque<Card>(); //construct w/empty deck
    }
    //methods
    public void addCard(Card c) {
        playerdeck.addLast(c);
    }
    public String toString() {
        String sb = "";
        for (var card : playerdeck) {
            sb += card.getValue() + card.getSuit() + "\n";
        }
        return sb;
    }
    public boolean isEmpty() {
        if (playerdeck.size()!=0) {
            return false;
        }
        else {
            return true;
        }
    }
    public int size() { return playerdeck.size(); }
    public Card pop() {
        Card topCard = playerdeck.pop();
        return topCard;
    }
}

Ответы [ 2 ]

0 голосов
/ 04 мая 2020

Я не осознавал, что, поскольку в своем выражении if я использовал warRound, я снова вызывал функцию. Вместо этого я устанавливаю переменную для результата. то есть

roundResult = warRound(player1, player2, p1List, p2List);

, а затем вместо этого я использовал переменную в моих if выражениях, например:

if (roundResult == player1) {
                    player1.addCard(p1card);
                    player1.addCard(p2card);
                    //check card counts
                    System.out.println("Player One card count: " + player1.size());
                    System.out.println("Player Two card count: " + player2.size());
                } 
0 голосов
/ 15 апреля 2020

@ ScaryWombat я думаю == сравнение достаточно хорошее. мы хотим сравнить реальную ссылку на объект.

@ Шейла, можешь ли ты опубликовать класс Player, чтобы понять его методы? я подозреваю, что это метод .pop () и метод isEmpty ()

, и я думаю, что было бы лучше отладить, если вы добавите количество карт с каждым игроком после каждой войны.

...