Page 1 of 2 12 LastLast
Results 1 to 20 of 25
Like Tree1Likes

Thread: How to write a method within a method?

  1. #1
    Kanada is offline Member
    Join Date
    Mar 2017
    Posts
    14
    Rep Power
    0

    Default How to write a method within a method?

    Java Code:
    public void start() {
    		System.out.println("Start!"); 
    		gamet1.battle();
    	}
    	
    	public void battle() {
    		System.out.println(card1Hp - card2Apc); 
    	}
    	
    	public static void main(String[] args) {
    		Game1 gamet1 = new Game1();
    		gamet1.start();
    	}
    I'm trying to write a game and I'm a complete noob even though I've spent months going through a Java book.
    My main method activates start method and in there I want to activate a battle method but that doesn't work. My plan really was for battle method to active another method called attack that takes in player 1 and runs the attack sequence. Then runs attack method again that takes int player 2 and runs the attack code but with player 2 instead.

    How would I get battle() to start running in start()?
    I want to create a turn based system and I'm not sure if this is the direction and coding method I should be heading in as well. Can anybody point me int the right directions?

  2. #2
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,964
    Rep Power
    7

    Default Re: How to write a method within a method?

    You need to learn about using fields in classes and parameters in method signatures. You can keep track of the current player using a field, or via passing it as parameter. The disadvantage of the latter is that method signatures are cluttered with information and adding parameters to it makes it only worse. What you're looking for a way to keep state. Here's an example. It does not make sense as a game, but it's to show you how to keep state withing your game class. Obviously there are 1000 ways to do this, this is just one of them. I tried to keep it simple.

    Here you go:

    Java Code:
    class Game1 {
    	private int currentPlayer;
    
    	public static void main(String[] args) {
    		Game1 gamet1 = new Game1();
    		gamet1.setCurrentPlayer(1);
    		gamet1.start();
    	}
    	
    	public void start() {
    		System.out.println("Start!"); 
    		gamet1.battle();
    	}
    	 
    	public void battle() {
    	    if ( getCurrentPlayer() == 1) {
    		    System.out.println(card1Hp - card2Apc); 
    		}
    		else if ( getCurrentPlayer() == 2 ) {
    		    System.out.println(card2Hp - card1Apc); 
    		}
    		changeTurn();
    	}
    
        public void setCurrentPlayer(int player) {
    	    this.currentPlayer = player;
    	}
    	
    	public int getCurrentPlayer() {
    	    return this.currentPlayer();
    	}
    	
    	public void changeTurn() {
    	    if ( getCurrentPlayer() == 1) {
    		    setCurrentPlayer(2);
    		}
    	    else if ( getCurrentPlayer() == 2) {
    		    setCurrentPlayer(1);
    		}
    	}
    
    }
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  3. #3
    Kanada is offline Member
    Join Date
    Mar 2017
    Posts
    14
    Rep Power
    0

    Default Re: How to write a method within a method?

    So I redesigned the code using states and is something like this heading into the right direction?
    I used a while loop to keep the battle going until something dies. I couldn't really implement that sort of setter getter thing you have going in your tips though. Would my method have major drawbacks without using that?

    Java Code:
    public class Game3 {
        public Game3 gamet3;
        public int card1Hp = 100;
        public int card2Hp = 80;
        public int card1Apc = 20;
        public int card2Apc = 30;
        public int player = 1;
        
        public void start(){
            System.out.println("1");
            battle();
        }
        
        public void battle(){
            while(card1Hp > 0 && card2Hp > 0) {
            System.out.println("player is " + player); //gives one
    
                    if (player == 1){
                        card1Hp = card1Hp - card2Apc;
                        System.out.println(card1Hp);
                    }
                    else if(player == 2 ) {
                        card2Hp = card2Hp - card1Apc;
                        System.out.println(card2Hp);
                    }
                changeTurn();
            }
            System.out.println("Game Over");
        }
        
        public void changeTurn(){
            if(player == 1){
                player = 2;
                System.out.println("change turn if " + player);
            }else if(player == 2){
                player = 1;
                System.out.println("change turn else " + player);
            }
            battle();
        }
        
        public static void main(String[] args){
            Game3 gamet3 = new Game3(); 
            gamet3.start();
        }
    }
    
    //public static void main(String[] args){}.
    //Decides player 1 or 2, launches start
    //start launches battle(). Player 1 gives if.
    //Player 2 gives else
    //battle's last method is change turn.
    //if player 1 then player = 2. launches battle again.
    
    //how do i set player value as 1 or 2 in psvm?
    //changeTurn if player 1 change to 2.
    //else if player 2 change to player 1.
    //changeTurn() launches battle method again at the end?
    
    //Where to end battle()? How to end start().
    //End when card1Hp OR card2Hp <= 0.
    //While loop.
    //if hp loop < 0 exit out of battle?
    //nesting the conditions of players,
    //if Hp > 0 then play condtions to battle()
    //else if Hp <= 0 then end the start and print GAMEOVER.
    Last edited by Kanada; 12-26-2017 at 07:35 PM.

  4. #4
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,964
    Rep Power
    7

    Default Re: How to write a method within a method?

    You're making good progress. I used getters and setters because sooner or later you are going to split the class into multiple classes and some might need access to the data contained in other classes. Keeping everything in one class will become a problem very soon. What happens if player 3 enters the stage? What happens if you start using weapons? Keeping state in ONE single place is very hard and error prone.

    Since I like creating these concepts, I have created an example of what happens when you split your code in separate classes. Don't worry if you don't understand all of it. I will answer questions if you have any.

    Disclaimer: this is not perfect, but meant for showing you the use of getters and setters, and how clear your code will become once you start splitting code into separate classes and keep responsibilities where they are supposed to be. Although it seems to be a lot more work, it's not. I agree it's more keystrokes, but my editor (IntelliJ IDEA) has generated/completed 75% if the code so it's not that bad.

    (It's quite a few classes, so copy and paste each into a separate file named after the classname, so class Player has to go in a file called Player.java.)

    Game:
    Java Code:
    public class Game {
        private Player player1;
        private Player player2;
    
        private Player currentPlayer;
    
        public static void main(String[] args) {
            Player player1 = new Player("Player 1");
            player1.setWeapon(new Club());
    
            Player player2 = new Player("Player 2");
            player2.setWeapon(new Sword());
    
    
            Game game = new Game(player1, player2);
            game.setCurrentPlayer(player1);
            game.startBattle();
        }
    
        public Game(Player player1, Player player2) {
            this.player1 = player1;
            this.player2 = player2;
        }
    
        public void startBattle() {
            while (!player1.isDead() && !player2.isDead()) {
                System.out.printf("Player is %s, health %s%n", currentPlayer.getName(), currentPlayer.getHealth());
                Player opponent = getOpponent();
                int health = opponent.getHealth();
                Weapon weapon = currentPlayer.getWeapon();
                int hit = weapon.hit();
                System.out.printf("Player %s strikes %s with a %s for %s points!%n", currentPlayer.getName(), opponent.getName(), weapon.getName(), hit);
                int afterHit = health - hit;
                opponent.setHealth(afterHit);
                System.out.printf("Player %s has %s health left!%n", opponent.getName(), opponent.getHealth());
    
                if (opponent.isDead()) {
                    System.out.printf("Battle ended, %s is dead. Victory for %s!%n", opponent.getName(), currentPlayer.getName());
                    break;
                }
    
                currentPlayer = opponent;
            }
        }
    
        public Player getCurrentPlayer() {
            return currentPlayer;
        }
    
        public Player getOpponent() {
            return getCurrentPlayer() == player1 ? player2 : player1;
        }
    
        public void setCurrentPlayer(Player currentPlayer) {
            this.currentPlayer = currentPlayer;
        }
    
    
    }
    Player:
    Java Code:
    public class Player {
        private String name;
        private int health = 100;
        private Weapon weapon;
    
        public Player(String name) {
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
    
        public int getHealth() {
            return health;
        }
    
        public void setHealth(int health) {
            this.health = health;
        }
    
        public Weapon getWeapon() {
            return weapon;
        }
    
        public void setWeapon(Weapon weapon) {
            this.weapon = weapon;
        }
    
        public boolean isDead() {
            return getHealth() < 0;
        }
    }
    Weapon:
    Java Code:
    import java.util.Random;
    
    public interface Weapon {
        public String getName();
        public int getMinimumDamage();
        public int getMaximumDamage();
    
        public default int hit() {
            return getMinimumDamage() + new Random().nextInt(getMaximumDamage() - getMinimumDamage());
        }
    }
    Club:
    Java Code:
    public class Club implements Weapon {
        @Override
        public String getName() {
            return "big wooden club";
        }
    
        @Override
        public int getMinimumDamage() {
            return 10;
        }
    
        @Override
        public int getMaximumDamage() {
            return 30;
        }
    }

    Sword:
    Java Code:
    public class Sword implements Weapon {
    
        @Override
        public String getName() {
            return "shiny elven sword";
        }
    
        @Override
        public int getMinimumDamage() {
            return 20;
        }
    
        @Override
        public int getMaximumDamage() {
            return 50;
        }
    }
    Output:
    Java Code:
    Player is Player 1, health 100
    Player Player 1 strikes Player 2 with a big wooden club for 29 points!
    Player Player 2 has 71 health left!
    Player is Player 2, health 71
    Player Player 2 strikes Player 1 with a shiny elven sword for 29 points!
    Player Player 1 has 71 health left!
    Player is Player 1, health 71
    Player Player 1 strikes Player 2 with a big wooden club for 25 points!
    Player Player 2 has 46 health left!
    Player is Player 2, health 46
    Player Player 2 strikes Player 1 with a shiny elven sword for 32 points!
    Player Player 1 has 39 health left!
    Player is Player 1, health 39
    Player Player 1 strikes Player 2 with a big wooden club for 20 points!
    Player Player 2 has 26 health left!
    Player is Player 2, health 26
    Player Player 2 strikes Player 1 with a shiny elven sword for 48 points!
    Player Player 1 has -9 health left!
    Battle ended, Player 1 is dead. Victory for Player 2!
    Last edited by SurfMan; 12-27-2017 at 06:44 PM. Reason: Edit: added output
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  5. #5
    Kanada is offline Member
    Join Date
    Mar 2017
    Posts
    14
    Rep Power
    0

    Default Re: How to write a method within a method?

    I was studying your code and I have a few questions unfortunately.
    To set weapon for player1 you write

    player1.setWeapon(new Club());

    Normally I see Club() as methods but Club only exists as a class you wrote. It takes public void setWeapon(Weapon weapon) from the player class. How come it works with putting new Club() into (Weapon Weapon)?

    I always get confused with the usage of "this". For:

    Java Code:
      public Game(Player player1, Player player2) {
            this.player1 = player1;
            this.player2 = player2;
        }
    Is the 'this' taking the instance variable at the very top of the class?
    public class Game {
    private Player player1;
    As in this.player1 is bascally saying Game.player1? ...or something?

    There's probably tons of stuff going over my head in your code that my brain is just frying trying to think of it and make logical questions out of it...

    I redeveloped my game mechanics and have it solidly visualised on how it should work out with consideration for future inputting designs aw well and so I redeveloped it with influence from how you coded:

    Java Code:
    public class Game7 {
    	public Game7 gamet7;
    	private Player player1;
    	private Player player2;
    	private Player currentPlayer;
    	private static int randomNumber;
    	
    	public static void main(String[] args) {
    		Player player1 = new Player("Player 1");
    		Player player2 = new Player("Player 2");
    		System.out.println(player1.getName()); 
    		System.out.println(player2.getName()); 
    		//randomNumber = RandomNumberGenerator.getRandIntBetween(1,10); 
    		//System.out.println(randomNumber); 
    		
    		Game7 gamet7 = new Game7(player1, player2);
    		gamet7.setCurrentPlayer(player1);
    		System.out.println(gamet7.getCurrentPlayer());
    		gamet7.start();
    	} 
    	
    	public void start(){
    		startBattle();
    	}
    	
    	public void startBattle() {
    		
    	}
    	
    	public Game7(Player player1, Player player2) {
    		this.player1 = player1; // Inputs Game7.player1 as player1;
    		this.player2 = player2; // Inputs Game7.player2 as player2;
    	}
    	
    	public Player getCurrentPlayer() { 
    		return currentPlayer;	//used in psvm 
    	} 
    	
    	public void setCurrentPlayer(Player currentPlayer) {
    		this.currentPlayer = currentPlayer;	//used in psvm to set player 
    	}
    }
    A card class to hold my card datas:

    Java Code:
    public class Cards {
    	private int card1Hp = 100;
        private int card2Hp = 80;
        private int card3Hp = 90;
        private int card4Hp = 70;
        private int card5Hp = 60;
        private int card6Hp = 50;
        private int card7Hp = 110;
        private int card8Hp = 120;
        private int card9Hp = 130;
        private int card10Hp = 140;
       
        private int card1Apc = 20;
        private int card2Apc = 30;
        private int card3Apc = 10;
        private int card4Apc = 40;
        private int card5Apc = 50;
        private int card6Apc = 60;
        private int card7Apc = 40;
        private int card8Apc = 20;
        private int card9Apc = 10;
        private int card10Apc = 30;
        
        public int getCard1Apc (int card1Apc) {return card1Apc;}
        public int getCard2Apc (int card2Apc) {return card2Apc;}
        public int getCard3Apc (int card3Apc) {return card3Apc;}
        public int getCard4Apc (int card4Apc) {return card4Apc;}
        public int getCard5Apc (int card5Apc) {return card5Apc;}
        public int getCard6Apc (int card6Apc) {return card6Apc;}
        public int getCard7Apc (int card7Apc) {return card7Apc;}
        public int getCard8Apc (int card8Apc) {return card8Apc;}
        public int getCard9Apc (int card9Apc) {return card9Apc;}
        public int getCard10Apc (int card10Apc) {return card10Apc;}
        
        public void setCard1Apc (int card1Apc) {this.card1Apc = card1Apc;}
        public void setCard2Apc (int card2Apc) {this.card2Apc = card2Apc;}
        public void setCard3Apc (int card3Apc) {this.card3Apc = card3Apc;}
        public void setCard4Apc (int card4Apc) {this.card4Apc = card4Apc;}
        public void setCard5Apc (int card5Apc) {this.card5Apc = card5Apc;}
        public void setCard6Apc (int card6Apc) {this.card6Apc = card6Apc;}
        public void setCard7Apc (int card7Apc) {this.card7Apc = card7Apc;}
        public void setCard8Apc (int card8Apc) {this.card8Apc = card8Apc;}
        public void setCard9Apc (int card9Apc) {this.card9Apc = card9Apc;}
        public void setCard10Apc(int card10Apc){this.card10Apc = card10Apc;}
        
        public void setCard1Hp (int card1Hp) {this.card1Hp = card1Hp;}
        public void setCard2Hp (int card2Hp) {this.card2Hp = card2Hp;}
        public void setCard3Hp (int card3Hp) {this.card3Hp = card3Hp;}
        public void setCard4Hp (int card4Hp) {this.card4Hp = card4Hp;}
        public void setCard5Hp (int card5Hp) {this.card5Hp = card5Hp;}
        public void setCard6Hp (int card6Hp) {this.card6Hp = card6Hp;}
        public void setCard7Hp (int card7Hp) {this.card7Hp = card7Hp;}
        public void setCard8Hp (int card8Hp) {this.card8Hp = card8Hp;}
        public void setCard9Hp (int card9Hp) {this.card9Hp = card9Hp;}
        public void setCard10Hp (int card10Hp) {this.card10Hp = card10Hp;}
        
        public int getCard1Hp (int card1Hp) {return card1Hp;}
        public int getCard2Hp (int card2Hp) {return card2Hp;}
        public int getCard3Hp (int card3Hp) {return card3Hp;}
        public int getCard4Hp (int card4Hp) {return card4Hp;}
        public int getCard5Hp (int card5Hp) {return card5Hp;}
        public int getCard6Hp (int card6Hp) {return card6Hp;}
        public int getCard7Hp (int card7Hp) {return card7Hp;}
        public int getCard8Hp (int card8Hp) {return card8Hp;}
        public int getCard9Hp (int card9Hp) {return card9Hp;}
        public int getCard10Hp (int card10Hp) {return card10Hp;} 
    }
    I'm having a problem with developing a new battle() method it for it. For now I'm removing my old game loop and simplifying the whole system.
    Basically sort of similar to your code, a currentPlayer.getsRandomCard, Opponenent.getsRandomCard. (this isn't the way to write it probably but you get the idea hopefully)(Player is assigned random card from that Cards class)

    Whoever has the card with a higher cardApc wins.
    (I'm going to ignore cardHp for now, that comes in future design).
    Right now I have a method that allows me to produce random numbers (1-10) but I want to assign this to the cards in the card class.

    Bascially player1 gets random number 5 so he gets card5 with the properties: card5Hp = 60; card5Apc = 50;
    player2 gets random number 2 so he gets card2Hp = 80; card2Apc = 30;
    Player 5 wins because card5Apc > card2Apc. (The idea of Hp will come in later).

    Should I create an individual card class within my Cards class.
    eg. public class card1stats{getCard1Apc, getCard1Hp} //and copy for all 10 cards within my class called Cards where all my variables values are.
    This probably isn't the way to write it but sort of that idea if you know what I mean.
    How can I get the players to getCardstats and compare the cardApc data inside? How would I bring it into my battle() class? would it be like:
    gamet7.Cards.card.card1stats //Something like that, where card1Stats would contain its card1Apc and card1Hp values?

    Sorry for the lenghty comment and all the questions, all this is like some kind of impossible spaghetti code to me right now even though I have my idea fully formed this time for my game mechanics.
    Last edited by Kanada; 12-29-2017 at 03:53 AM.

  6. #6
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,964
    Rep Power
    7

    Default Re: How to write a method within a method?

    I can always appreciate people making an effort. I'll try and comment where I can.

    Quote Originally Posted by Kanada View Post
    I was studying your code and I have a few questions unfortunately.
    To set weapon for player1 you write

    player1.setWeapon(new Club());

    Normally I see Club() as methods but Club only exists as a class you wrote. It takes public void setWeapon(Weapon weapon) from the player class. How come it works with putting new Club() into (Weapon Weapon)?
    This is called polymorphism (More info here). Club implements the Weapon interface. Think of it like this: I have a Weapon interface. It defines behaviour for a weapon. We all know what a weapon does, but you can't go to the store and buy a literal "weapon". The person behind the counter will always ask: "What kind of weapon?". That's where new Club() and new Sword() come in. They both implement Weapon so they MUST conform to that behaviour, but they each do it slightly differently. It's a nice universal way of letting the Player use different weapons without coding setClub(), setSword() setGun() etc.

    Quote Originally Posted by Kanada View Post
    I always get confused with the usage of "this". For:

    Java Code:
      public Game(Player player1, Player player2) {
            this.player1 = player1;
            this.player2 = player2;
        }
    Is the 'this' taking the instance variable at the very top of the class?
    public class Game {
    private Player player1;
    As in this.player1 is bascally saying Game.player1? ...or something?
    The keyword "this" refers to the current object (More info here). In my example, the field player1 (declared at the top of the class) and the parameter for player 1 are both named "player1". If I left out "this" it would read player1=player1. And that would assign the value to the parameter itself and not to the field. I make it a habit to refer to fields using "this". That way I never run into confusion of where the variable lives.

    Quote Originally Posted by Kanada View Post
    There's probably tons of stuff going over my head in your code that my brain is just frying trying to think of it and make logical questions out of it...
    Those who ask will become smarter :)


    Quote Originally Posted by Kanada View Post
    A card class to hold my card datas:
    ...snip...
    There is a nice opporunity to clean up the Cards class. As soon as you press CTRL-C and then CTRL-V a few times, you should step away from your keyboard and think: "There should be an easier way to do this". You should define what a card looks like. Think of it as a blueprint. Form your code I see it has APC and HP as properties including the getters and setters. So your Card class would look like this:
    Java Code:
    public class Card {
        private int apc;
        private int hp;
    
        public Card(int apc, int hp) {
            this.apc = apc;
            this.hp = hp;
        }
    
        public int getApc() {
            return apc;
        }
    
        public void setApc(int apc) {
            this.apc = apc;
        }
    
        public int getHp() {
            return hp;
        }
    
        public void setHp(int hp) {
            this.hp = hp;
        }
    }
    Now in your game you need several different cards. For convenient access, we can define a class called Deck that holds a undefined number of Card objects. It internally uses a List of Card, written as List<Card> (That's called generics, More info here). The getRandomCard() method generates a number between 0 and the number of cards in the deck (exclusive). It then uses that number to grab the Card from the List. It could look like this:
    Java Code:
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    
    public class Deck {
        private List<Card> cards;
    
        public Deck() {
            this.cards = new ArrayList<>();
        }
    
        public void addCard(Card card) {
            this.cards.add(card);
        }
    
        public Card getRandomCard() {
            int randomIndex = new Random().nextInt(this.cards.size());
            return cards.get(randomIndex);
        }
    }
    When you initialize your game you can add a number of cards to the deck. If each player gets a Deck, you could add it to the Player class. I've modified the Player class to have a Deck:
    Java Code:
    public class Player {
        private String name;
        private int health = 100;
        private Weapon weapon;
        private Deck deck;
    
        public Player(String name) {
            this.name = name;
    
            this.deck = new Deck();
            this.deck.addCard(new Card(20, 100));
            this.deck.addCard(new Card(30, 80));
            this.deck.addCard(new Card(10, 90));
        }
    
        public Card getRandomCard() {
            return this.deck.getRandomCard();
        }
    ...snip...
    In the above example, I add new Card objects to the deck when the player is created (I would normally have done this with a static factory, but that would introduce new concepts. We have enough going on as it is right now :)))

    So, now to check for a win. Your rule says: highest APC wins. So in your battle, you get each card and start comparing:
    Java Code:
    Card currentPlayerRandomCard = currentPlayer.getRandomCard();
    Card opponentRandomCard = opponent.getRandomCard();
    
    if (currentPlayerRandomCard.getApc() > opponentRandomCard.getApc()) {
         //current player wins!
    }
    else {
         //opponent wins
    }
    A possible improvement would be to have do the "win-check" not in the Game, but in the Card class itself. I added a "beats" method so you can have the Card class determine if it's better than the other card. See if you understand this example:
    Java Code:
    public class Card {
        private int apc;
        private int hp;
    
        public Card(int apc, int hp) {
            this.apc = apc;
            this.hp = hp;
        }
        
        public boolean beats(Card otherCard) {
            return this.getApc() > otherCard.getApc();
        }
    
    ...snip....
    In your battle, you can do a slightly easier check now, but the biggest advantage is that you now have only one place that determines when one card beats the other, instead if it being scattered across your code. If that win-rule changes, you now only have ONE place where you need to change the rule:

    Java Code:
    Card currentPlayerRandomCard = currentPlayer.getRandomCard();
    Card opponentRandomCard = opponent.getRandomCard();
    
    if (currentPlayerRandomCard.beats(opponentRandomCard)) {
        //current player wins!
    }
    else {
        //opponent wins
    }
    I hope I am not overloading you with information. I also hope I gave you some inspiration to keep going. I am looking forward to your progress.

    Feel free to come back for more questions and answers.

    All the best.

    Surf
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  7. #7
    Kanada is offline Member
    Join Date
    Mar 2017
    Posts
    14
    Rep Power
    0

    Default Re: How to write a method within a method?

    Okay here's what I put together so far and I have tons of questions unfortunately.

    Class Game:
    Java Code:
    public class Game8 {
    	public Game8 gamet8;
    	private Player player1;
    	private Player player2;
    	private Player currentPlayer;
    	private Player opponent;
    	private static int randomNumber;
    	private Deck2 deck2;
    	
    	public static void main(String[] args) {	
    		Player player1 = new Player("Player 1"); //Inputs "Player 1" as name into class Player
    		Player player2 = new Player("Player 2");
    		System.out.println(player1.getName()); //gets name from class Player getName();
    		System.out.println(player2.getName()); 
    		//randomNumber = RandomNumberGenerator.getRandIntBetween(1,5); 
    		//System.out.println(randomNumber); 
    		
    		Deck2 deck2 = new Deck2();
    		System.out.println("Deck 2 elements are "); 
                    System.out.println(deck2.printdeck2());  //Is this how to get
    		System.out.println(deck2.deck2.get(0)); 	//trying to get element from class Deck2, How?
    		
    		Game8 gamet8 = new Game8(player1, player2);
    		gamet8.setCurrentPlayer(player1);
    
    		gamet8.start();
    	} 
    	
    	public void start(){
    		System.out.println("Start Battle"); 
    		startBattle();
    	}
    	
    	public void startBattle() {
    		
    		/*Card currentPlayerRandomCard = currentPlayer.getRandomCard(); //from class Deck return method
    		Card opponentRandomCard = opponent.getRandomCard(); 
    		 
    		if (currentPlayerRandomCard.getApc() > opponentRandomCard.getApc()) {
    		     //current player wins!
    			System.out.println("You Win!"); 
    		}
    		else {
    		     //opponent wins
    			System.out.println("Opponent Wins!"); 
    		}*/
    	}
    	
    	public Game8(Player player1, Player player2) {
    		this.player1 = player1; // Inputs Game8.player1 as player1;
    		this.player2 = player2; // Inputs Game8.player2 as player2;
    	}
    	
    	public Player getCurrentPlayer() { 
    		return currentPlayer;	//used in psvm 
    	} 
    	
    	public Player getOpponent() {
    		return getCurrentPlayer() == player1 ? player2 : player1;
    		
    	}
    	
    	public void setCurrentPlayer(Player currentPlayer) {
    		this.currentPlayer = currentPlayer;	//used in psvm to set player 
    	}
    	
    }
    class Player:
    Java Code:
    public class Player {
        private String name;
        private int health = 100;
        private Deck deck;
     
        public Player(String name) {
            this.name = name;
     
            /*this.deck = new Deck();				//Create deck obj for player1/2
            this.deck.addCard(new Card(20, 100));	//can't add to deck Array of class Deck?
            this.deck.addCard(new Card(30, 80));	// Using Deck's addCard method to add to arrayList
            this.deck.addCard(new Card(10, 90));
            this.deck.addCard(new Card(40, 100));
            this.deck.addCard(new Card(50, 80));
            this.deck.addCard(new Card(60, 90));*/
        }
     
        public Card getRandomCard() {
            return this.deck.getRandomCard();  //player1/2 uses getRandomCard() from Deck
        }
        
        public String getName() {
        	return name;
        }
    }
    class Deck:
    Java Code:
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
     
    public class Deck {
        private List<Card> cards;
     
        public Deck() {
            this.cards = new ArrayList<>();		//Player1/2 creates Deck array holding card objects?
        }
     
        public void addCard(Card card) {
            this.cards.add(card);		  //Called by Player to add card obj that has apc and hp
        }
     
        public Card getRandomCard() {
            int randomIndex = new Random().nextInt(this.cards.size()); //List called cards
            return cards.get(randomIndex);		//Random().nextInt gets a random element in cards?
        }
    }
    class RandomNumberGenerator:
    Java Code:
    import java.util.Random;
    
    public class RandomNumberGenerator {
    	private static Random rand = new Random();
    	public static int getRandIntBetween(int lowerBound, int upperBound) {
    		return rand.nextInt(upperBound - lowerBound) + lowerBound;
    	}
    	public static int getRandInt(int upperBound) {
    		return rand.nextInt(upperBound);
    	}
    }
    class Deck2:
    Java Code:
    import java.util.ArrayList;
    
    public class Deck2 {
    	private String card1;
        public  ArrayList<String> deck2 = new ArrayList<String>();
        deck2.add("card1");											//cant add to deck?
    
        public void addtodeck2(){
        	deck2.add("card1");
        }
        
        public void printdeck2(){
        	System.out.println("Deck2"); 
        	//System.out.println(deck2.get[0]); 
        }
    }

    After a lot failing to try to understand it, I've gotten to the point of trying to test if I could create my own arrayList becuase there's some problem with adding cards in the class Player. So in this Deck2, I can't even add a string element into my ArrayList. Is this the core of my problem with the class Player as well. Normally that arrayListName.add worked in my other test in public static void main(String[] args){} but it breaks down when trying to use that .add method in another class?

    And if I'm trying to get the elements in Deck2, I would write deck2.printdeck2(); in my public static void main(String[] args){} ?
    And I should just make sure I create an instance of that class I'm trying to use in my main game class right called Deck2 deck;?

    For creating an arrayList why do you use List and then arrayList? Is this basically how you would create an ArrayList if you want the Player object to take in list? My question is probably confusing to you, I'm not sure what I'm trying to ask myself...

    Java Code:
     private List<Card> cards;
     
        public Deck() {
            this.cards = new ArrayList<>();		//Player1/2 creates Deck array holding card objects?
        }
    Sorry, this comment of questions is a mess, just like my mind right now, trying to string together all this code in my head.

  8. #8
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,964
    Rep Power
    7

    Default Re: How to write a method within a method?

    Keep asking questions. I can see you're getting to understand this.

    When I type List<Card> cards = new ArrayList><();, this means: declare a variable "cards" that will contain an object that knows how to behave like a List that contains Card objects. How it's actually implemented, (how it works internally and what benefits come with it) depends on the object I create, in this case a simple ArrayList. There are a lot more objects that behave as a List (LinkedList, SortedList, Vector, a list(no pun intended can be found here). This is basically the same as typing: Weapon w = new Club(). Declare a variable w that contains objects that behave like weapons. How it's implemented, how the weapon works, I don't care after this. All I know It got a Club and a Sword. This is also polymorphism, and you will find it a lot in (professional) code. To clarify,m it's perfectly fine to say: Arraylist cards = new ArrayList(). But that would be a problem when you later decide your list needs to be a SortedList, which means you would have to dig through all your code and change all ArrayLists into SortedLists.

    Your Deck2 class contains a statement deck2.add("card1") that is not inside a method. Statements like those need to be either in the contructor or a method. It cannot dangle somewhere in the class like that.

    I always imagine that I have to write an API for other programmers to use. So if i were a game designer, and I would have to use the code that you wrote, would I be interested to know how you organise your Deck? No, I'm not. I want to create a Deck, add cards, and be able to get a random card. That's why the Deck class exists. So in the Deck class you write methods that I can use to do that. The Deck has it's own responsibilities. This is called [URL="https://www.tutorialspoint.com/java/java_encapsulation.htm"]encapsulation/URL]. It means I have put the ArrayList in the Deck class so I can organize the Deck internally, but the programmer that uses your code (that is actually you), does not have to worry about how it works internally, and just use the methods that you give to him.

    My version of the random number is exactly the same as yours, be it that you keep hold the Random object and I create a new one every time you need a new random number. In this particular case, either way is good.

    I am not sure why you have problems in line 10 of the Player class using the Deck. Can you post the error you got? Don't let errors in compiling stop you. Instead, learn to examine the compiler message so you know what to change. Remember to post any compile or runtime errors you get. That greatly increases the chances of me (us) explaining it and telling you where you need to change stuff to make it work.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  9. #9
    Kanada is offline Member
    Join Date
    Mar 2017
    Posts
    14
    Rep Power
    0

    Default Re: How to write a method within a method?

    It turns out I was taking the ternary operator from the previous code for turn base action (I'm removing that for now but it will come in later) and it was missing a player2 setter as an opponent player method. I've added lifepoints to the class Player and so they keep drawing and losing until one player's lifepoints reduces to 0. So far it's become where I also added in cardId with the Apc's and hp's in Card class:

    Java Code:
    public class Game10 {
    	public Game10 gamet10;
    	private Player player1;
    	private Player player2;
    	private Player currentPlayer;
    	private Player opponentPlayer;
    	
    	public static void main(String[] args) {	
    		Player player1 = new Player("Player 1"); //Inputs "Player 1" as name into class Player
    		Player player2 = new Player("Player 2");
    		/*System.out.println(player1.getName()); //gets name from class Player getName();
    		System.out.println(player2.getName());  */
    
    		Game10 gamet10 = new Game10(player1, player2);
    		gamet10.setCurrentPlayer(player1);
    		gamet10.setOpponentPlayer(player2);
    
    		gamet10.start();
    	} 
    	
    	public void start(){
    		System.out.println("Start Battle"); 
    		startBattle();
    		
    		if(currentPlayer.getLifePoints()>0){
    			System.out.println("You Win!"); 
    		}else{
    			System.out.println("Opponent Wins"); 
    		}
    		
    		System.out.println("Battle Finished"); 
    	}
    	
    	public void startBattle() {
    		while (!player1.isDead() && !player2.isDead()){
    			Card currentPlayerRandomCard = currentPlayer.getRandomCard(); //from class Deck return method
    			//System.out.println(currentPlayerRandomCard.getApc()); //works getApc from getRandomCard()
    			Card opponentRandomCard = opponentPlayer.getRandomCard(); 
    			
    			int currentPlayerLifePoints = currentPlayer.getLifePoints();
    			int opponentPlayerLifePoints = opponentPlayer.getLifePoints();
    			
    			System.out.println("Player 1 Lifepoints = " +  currentPlayerLifePoints); 
    			System.out.println("CardId = " + currentPlayerRandomCard.getCardId()+ " CardApc = " + currentPlayerRandomCard.getApc());
    			System.out.println("Player 2 Lifepoints = " +  opponentPlayerLifePoints); 
    			System.out.println("CardId = " + opponentRandomCard.getCardId()+ " CardApc = " + opponentRandomCard.getApc());
    			
    			if (currentPlayerRandomCard.getApc() == opponentRandomCard.getApc()){
    				System.out.println("Draw! Draw again." + "\n"); 
    				startBattle();
    				
    			} else if (currentPlayerRandomCard.getApc() > opponentRandomCard.getApc()) {
    				//currentPlayer wins round!
    				System.out.println("You Win the round!" + "\n" ); 
    				int diff = currentPlayerRandomCard.getApc() - opponentRandomCard.getApc();
    				//Difference in Apc will be deducted from loser's LifePoints
    				System.out.println("Difference in Apc = " + diff); 
    				opponentPlayer.setLifePoints(opponentPlayerLifePoints - diff);
    				System.out.println("Player2 LifePoints after deduction= " + opponentPlayer.getLifePoints() +"Lp" + "\n"); 
    			} else {
    				//opponentPlayer wins round!
    				System.out.println("Opponent Wins the round!" + "\n");  
    				int diff = opponentRandomCard.getApc() - currentPlayerRandomCard.getApc();
    				//Difference in Apc will be deducted from loser's LifePoints
    				System.out.println("Difference in Apc = " + diff);
    				currentPlayer.setLifePoints(currentPlayerLifePoints - diff);
    				System.out.println("Player1 LifePoints after deduction=" + currentPlayer.getLifePoints() +"Lp"+  "\n"); 
    			}
    		}	
    	}
    	
    	public Game10(Player player1, Player player2) {
    		this.player1 = player1;						 // Inputs Game10.player1 as player1;
    		this.player2 = player2;						 // Inputs Game10.player2 as player2;
    	}
    	
    	public void setCurrentPlayer(Player currentPlayer) {
    		this.currentPlayer = currentPlayer;	//used in psvm to set player 
    	}
    	
    	public Player setOpponentPlayer(Player opponentPlayer){
    		return this.opponentPlayer = opponentPlayer;
    	}
    }

    I'm going to add card types where each card is whether its fire/water/grass type and card gets a boost in a random range between 10-20% maybe. I feel like I should focus on the next, most important part though in getting player interaction.

    The main feature that's really important is that each players draws 5 cards and the player chooses which one he wants to place down. I guess this would be done by scanner method where currentPlayer would type in 1-5 to place a card down since everythings a text game so far. I do wish to go beyond text interaction further down the line and I'm not sure if designing text benefits future development when I hope to move on to a more graphical interface? The AI I guess would just randomly choose a card from its hand.
    This is a bit broad but how should I go about holding 5 cards for the players features and then allowing player to choose from? It's a bit of a huge step...

  10. #10
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,964
    Rep Power
    7

    Default Re: How to write a method within a method?

    Happy New Year! Nice to see you're making progress.

    One tip I can give you when doing Object Oriented Programming, is to write out verbosely what you want to do, then take the nouns: they are a good candidate for being classes, take the verbs: they are good candidates for methods. Ofcourse this doesn't always work, but it gives you a place to start.

    First a nitpick: the public Game10 gamet10 doesn't do anything in your class. You never assign a value to it, so you can remove it.

    Second, you can create a class "Hand" that holds any given number of cards and add a Hand field to the Player class. You should probably remove the Deck from the Player since a Player does not need to have a Deck, only a Hand. Even though you only have 5 cards, I would not have 5 fields (Card card1, Card card2 etc). I would still use a List<Card> to store them. Alos, since you now have to deal with stupid users (they will input anything to break your program), you are going to need checks on a few things, for example maximum number of cards and range checks.

    Java Code:
    import java.util.ArrayList;
    import java.util.List;
    
    public class Hand {
        public static final int MAX_CARDS = 5;
    
        private List<Card> cards;
    
        public Hand() {
            cards = new ArrayList<>();
        }
    
        public void addCard(Card card) {
            if (cards.size() > MAX_CARDS) {
                throw new IllegalArgumentException("A hand can not contain more than " + MAX_CARDS);
            }
    
            cards.add(card);
        }
    
        public Card drawCard(int index) {
            if (index < 0 || index >= MAX_CARDS) {
                throw new IllegalArgumentException("Index must be between 0 (inclusive) and " + MAX_CARDS + " (exclusive)" );
            }
    
            Card card = cards.get(index);
            if (card == null) {
                throw new IllegalArgumentException("Position " + index + " does not contain a card");
            }
            else {
                return card;
            }
        }
    
    }
    Just remember that drawCard receives an index as parameter, so when you get user input, you still have to substract 1. (If the player wants card 1, you want to call drawCard(0)).

    A quick explanation of that magical public static final int MAX_CARDS. If you start hardcoding the number 5 everywhere, you're going to be in trouble when you decide to change that number to 6. Using a public static final field makes sure I can use it everywhere without hardcoding it.

    public: all classes/objects can access this field
    static: the field belongs to the class, and not on a specific object
    final: it cannot be changed by the user (or the one that uses your code)
    int: an integer

    If you need to learn about static (and you should), read this.

    Getting user input is simple: use a Scanner that connects to System.in. The internet is littered with examples.
    Java Code:
    Scanner scanner = new Scanner(System.in);
    
    int cardInput = -1;
    boolean validInput = false;
    while (!validInput) {
        try {
            cardInput = scanner.nextInt();
            System.out.println("card = " + cardInput);
            validInput = true;
        }
        catch (InputMismatchException e) {
            System.out.println("Please input a number");
        }
        scanner.nextLine();
    }
    
    //do something with cardInput here.
    Now, we need a way to create a Hand object. We can do that ourselves, but I feel that a Deck is the perfect place to do that. It can have a method called dealHand() that creates a Hand, fills it with cards and returns it.
    Java Code:
    public Hand dealHand() {
        Hand hand = new Hand();
        for (int i = 0; i < Hand.MAX_CARDS; i++) {
            hand.addCard(getRandomCard());
        }
        return hand;
    }
    Give the Game class a Deck field and in the constructor of Game assign it a new Deck():
    Java Code:
        public Game(Player player1, Player player2) {
            this.player1 = player1;
            this.player2 = player2;
            this.deck = new Deck();
            
            player1.setHand(deck.dealHand());
            player2.setHand(deck.dealHand());
        }
    Here's challenge for you: update the Deck class so it cannot hand out the same card twice. :)

    As for the AI, that's a whole different story. For now your best best is to return a random card from the hand, but when the game starts to come together, you probably want some sort of "intelligence", at least some rulebook that the AI needs to follow.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  11. #11
    Kanada is offline Member
    Join Date
    Mar 2017
    Posts
    14
    Rep Power
    0

    Default Re: How to write a method within a method?

    Happy New Year to you too. I'll still be on square one if it wasn't for your great help.

    I spent so much time trying stuff but I got really lost in the code and am just back to rewriting code in haphazard directions. So my objective right now is to just get the hand cards working where basically players would randomly place down card into the game loop (I'm ignoring scanner at the moment to try and take baby steps).

    So I created "class Hand" which has new arrayList called "hand".
    With "addCard(Card card)" in Hand, it tries to add 5 cards to "hand" but this throws me that illegal exception since in class Player there's more than 5 cards?

    drawCard(int index) in class "Hand" returns a card by putting 0-4 as a parameter to get a card from the "hand" arrayList.

    my class "Deck" contains that "dealHand()" that adds a random card to ensure that the "hand" array stays at 5 cards.
    In it it says hand.addCard(getRandomCard()) but I'm lost in where the getRandomCard() method is coming from? Is it using the method from the same class (in class Deck?):

    Java Code:
       public Card getRandomCard() {
            int randomIndex = new Random().nextInt(this.cards.size()); //List called cards
            return cards.get(randomIndex);		//Random().nextInt gets a random element in cards?
        }
    So in class "Game11" I set my player objects and create a deck object for both of them with "this.deck = new Deck();"

    then you call a method in class "Player" called:
    Java Code:
     player(1 and 2).setHand(deck.dealHand())
    so I created a method in Player like this to return whatever deck.dealHand gives me? Where dealHand in class "Deck" gives me 5 cards.

    I've been trying to rewrite my startBattle() game loop with the incorporation of using the hand mechanics but I lost in how to do things.
    In my setHand(). This is meant link to deck.dealHand but how and this has a return for hand object? I'm sorry I'm so lost that none of this is making sense to my simple mind...

    Although I can't code it I'll try to write it out in English that I think how all this code is supposed to work and how I can get my startBattle() out:
    1. Player object uses setHand() that somehow draws 5 cards.
    2. I get the index for these 5 drawn cards of the "hand" arrayList.
    3. I repeat this for opponentPlayer.
    4. I use a random number method to generate a number 0-4 called int rand1 and int rand2.
    5. rand1 number will be the card index I want to get from hand array and rand2 for opponent.
    6. With knowing what random card I got I can use the old gameloop I had.
    7. In the if else at the end I call removeCard(int cardIndexUsed) in my class Hand to remove that card from my hand array.
    8. I call dealHand in class Deck to add back one more card from Player class to my "hand" Array? I do some if statement that says it can't be the same cardId as the one removed since I've given them all cardId's.
    9. I then repeat loop until one player loses all his lifepoints.

    I do not know how I can give my player 1 and 2 their hand. Am I trying to return the object hand that contains the array and taking a random card out of that array in my Game class. I'm super lost in how I'm doing things. I can't figure out the setHand and how its supposed to work in all of this.


    class Game:
    Java Code:
    import java.util.Random;
    
    public class Game11 {
    	public Game11 gamet11;
    	private Player player1;
    	private Player player2;
    	private Player currentPlayer;
    	private Player opponentPlayer;
    	private Deck deck;
    	
    	public static void main(String[] args) {	
    		Player player1 = new Player("Player 1"); //Inputs "Player 1" as name into class Player
    		Player player2 = new Player("Player 2");
    		/*System.out.println(player1.getName()); //gets name from class Player getName();
    		System.out.println(player2.getName());  */
    
    		Game11 gamet11 = new Game11(player1, player2);
    		gamet11.setCurrentPlayer(player1);
    		gamet11.setOpponentPlayer(player2);
    
    		gamet11.start();
    	} 
    	
    	public void start(){
    		System.out.println("Start Battle"); 
    		startBattle();
    		
    		if(currentPlayer.getLifePoints()>0){
    			System.out.println("You Win!"); 
    		}else{
    			System.out.println("Opponent Wins"); 
    		}
    		
    		System.out.println("Battle Finished"); 
    	}
    	
    	public void startBattle() {
    		while (!player1.isDead() && !player2.isDead()){
    			Card currentPlayerRandomCard = currentPlayer.setHand(); 
    			Card opponentPlayerRandomCard = currentPlayer.setHand(); 
    			
    			
    			/*if (currentPlayerRandomCard.getApc() == opponentRandomCard.getApc()){
    				startBattle();
    			} else if (currentPlayerRandomCard.getApc() > opponentRandomCard.getApc()) {
    				
    				System.out.println("Player2 LifePoints after deduction= " + opponentPlayer.getLifePoints() +"Lp" + "\n"); 
    			} else {
    				
    			}*/
    		}	
    	}
    	
    	public Game11(Player player1, Player player2) {
    		this.player1 = player1;
    	    this.player2 = player2;
    	    this.deck = new Deck();
    	     
    	    player1.setHand(deck.dealHand());
    	    player2.setHand(deck.dealHand());
    	}
    	
    	public void setCurrentPlayer(Player currentPlayer) {
    		this.currentPlayer = currentPlayer;	//used in psvm to set player 
    	}
    	
    	public Player setOpponentPlayer(Player opponentPlayer){
    		return this.opponentPlayer = opponentPlayer;
    	}
    
    }
    class Player:
    Java Code:
    public class Player {
        private String name;
        private int lifePoints = 100;
        private Deck deck;
        
     
          public Player(String name) {
            this.name = name;
     
            this.hand = new Hand();								//Create deck obj for player1/2
            this.hand.addCard(new Card("c1", 20, 100, "fire"));		//can't add to deck Array of class Deck?
            this.hand.addCard(new Card("c2",30, 80, "fire"));		// Using Deck's addCard method to add to arrayList
            this.hand.addCard(new Card("c3",10, 90, "water"));
            this.hand.addCard(new Card("c4",40, 100, "grass"));
            this.hand.addCard(new Card("c5",50, 80, "fire"));
            this.hand.addCard(new Card("c6",60, 90, "water"));
            this.hand.addCard(new Card("c7",20, 90, "fire"));
            this.hand.addCard(new Card("c8",30, 90, "fire"));
            this.hand.addCard(new Card("c9",10, 90, "water"));
            this.hand.addCard(new Card("c10",30, 90, "grass"));
        }
     
        public Card getRandomCard() {
            return this.deck.getRandomCard();  //player1/2 uses getRandomCard() from Deck
        }
        
        public String getName() {
        	return name;
        }
        
        public int getLifePoints(){
        	return lifePoints;    	
        }
        
        public void setLifePoints(int lifePoints){
        	this.lifePoints = lifePoints;
        }
        
        public boolean isDead(){
        	return getLifePoints() < 0;
        }
        
    	public Card setHand() {
    		return this.deck.dealHand(); //Clearly wrong, No idea what to do with this...
    	}
    }
    class Deck:
    Java Code:
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
     
    public class Deck {
        private List<Card> cards;
     
        public Deck() {
            this.cards = new ArrayList<>();		//Player1/2 creates Deck array holding card objects?
        }
     
        public void addCard(Card card) {
            this.cards.add(card);		  //Called by Player to add card obj that has apc and hp
        }
     
        public Card getRandomCard() {
            int randomIndex = new Random().nextInt(this.cards.size()); //List called cards
            return cards.get(randomIndex);		//Random().nextInt gets a random element in cards?
        }
        
        public Hand dealHand() {
            Hand hand = new Hand();
            for (int i = 0; i < Hand.MAX_CARDS; i++) {
                hand.addCard(getRandomCard());
            }
            return hand;
        }
    }
    class Hand:
    Java Code:
    import java.util.ArrayList;
    import java.util.List;
    
    public class Hand {
    	   public static final int MAX_CARDS = 5;
    	   Deck deck;
    	   
    	   private List<Card> hand;
    	   
    	   public Hand() {
    	        hand = new ArrayList<>();
    	    }
    	   
    	   public void addCard(Card card) {
    	        if (hand.size() > MAX_CARDS) {
    	            throw new IllegalArgumentException("A hand can not contain more than " + MAX_CARDS);
    	        }
    	        hand.add(card);
    	    }
    	   
    	   //draw card from index of hand ArrayList
    	    public Card drawCard(int index) {
    	        if (index < 0 || index >= MAX_CARDS) {
    	            throw new IllegalArgumentException("Index must be between 0 (inclusive) and " + MAX_CARDS + " (exclusive)" );
    	        }
    	 
    	        Card card = hand.get(index);
    	        if (card == null) {
    	            throw new IllegalArgumentException("Position " + index + " does not contain a card"); 
    	        }
    	        else {
    	            return card;
    	        }
    	    }
    	    
    	    public void removeCard(int position) {
    		      if (position < 0 || position >= hand.size())
    		         throw new IllegalArgumentException("Position does not exist in hand: "
    		               + position);
    		      hand.remove(position);
    		 }
    }
    Last edited by Kanada; 01-03-2018 at 09:14 PM.

  12. #12
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,964
    Rep Power
    7

    Default Re: How to write a method within a method?

    Let's go back a step. Back to some basic Java.

    There are methods that you call that return nothing. Those are the ones that you write with "void": public void setName(...). This method does something for you and it returns nothing.
    And then there are methods that actually give you something in return: you write those with the type that it returns: public Hand dealhand(...). This method also does something, but it returns you whatever it needs to return, in this case a Hand object.

    When you write: player.setHand( deck.dealHand()), you are saying: I want to use whatever is returned from deck.DealHand() as parameter in player.setHand(...). It's basically a shortcut for writing this:
    Java Code:
    Hand hand = deck.dealHand();
    player.setHand(hand);
    You are breaking your own game rules. You said a hand should have 5 cards, but you are trying to add 10 in the Player constructor. So either change the maximum number of cards for each hand, or add less cards, or remove the check altogether and allow an arbitrary number of cards to be in the hand.

    You have to decide HOW to create the Player's Hand object. I chose to do it by doing deck.dealHand(), but you are creating a hand in the player constructor. Either one is fine, but you are trying to use it both and that will lead to errors and/or confusion.

    Also, you seem to be confused about the difference between Deck and Hand. In the Player class, the method getRandomCard() pulls a card from the Deck. you are also trying to assign this.hand = new Hand(); but the Player class does not HAVE a field of type Hand.

    Take a step back and think about this: you and me are playing poker. Texas Hold 'em if you will. The bank has a deck of cards from which one card is pulled out and given to each player to put in his hand.
    Take all the nouns and make those into objects:
    - Bank
    - Deck
    - Card
    - Player
    - Hand.

    Try to think of what each object has to do, what its responsibilities are.
    - A Bank has a Deck of Cards
    - A Bank needs to shuffle cards
    - A Bank has to give you a single card.
    - A Player has a Hand.
    - A Hand must be able to add a Card to its collection.

    When you encouter "has a", it's probably a field of that object: Bank has a Deck, Deck has Cards, Player has a Hand, Hand has Cards. (If it's plural, it's probably a List of that object, for example List<Card>)

    All verbs could be methods:
    - For Bank or Deck: public void shuffle() {...}
    - For Bank: public Card giveCard() {...}
    - For Hand: public void addCard(Card c) {...}

    You can closely model real life objects to program code. Even more so with card games in code, since they can be modelled very precise.
    Last edited by SurfMan; 01-05-2018 at 09:22 AM.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  13. #13
    Kanada is offline Member
    Join Date
    Mar 2017
    Posts
    14
    Rep Power
    0

    Default Re: How to write a method within a method?

    This is depressing but my game code is now a jumbled pile now after rewriting so many things.
    I didn't want to go for a bank class so I was trying something like this:
    1. Player contained the card stats and added to deck (like the old code).
    2. Created Hand class and ArrayList to hold cards.
    3. I tried to add 5 random cards from the deck ArrayList to the new hand ArrayList and this is where it never worked. I could never return some card from the ArrayList and then tell it to add to the ArrayList of my hand class.
    4. In class game, startBattle(), it would draw a random card from that hand ArrayList like the old code where I drew a random card from deck. (Just to keep things simple for now).

    It just became a mess that I could never get to work. My code now is just a hodge-podge pile of spaghetti like this and gone beyond redemption and comprehension. I do have my pokemon like type methods worked out though that uses loads of if else statements that I can readily code but I'm at a standstill with trying to get my startBattle() to at least be able to call one card from Hand array to it.

    Game11:
    Java Code:
    import java.util.Random;
    
    public class Game11 {
    	public Game11 gamet11;
    	private Player player1;
    	private Player player2;
    	private Player currentPlayer;
    	private Player opponentPlayer;
    	private Deck deck;
    	private Hand hand;
    	
    	public static void main(String[] args) {	
    		Player player1 = new Player("Player 1"); //Inputs "Player 1" as name into class Player
    		Player player2 = new Player("Player 2");
    		/*System.out.println(player1.getName()); //gets name from class Player getName();
    		System.out.println(player2.getName());  */
    
    		Game11 gamet11 = new Game11(player1, player2);
    		gamet11.setCurrentPlayer(player1);
    		gamet11.setOpponentPlayer(player2);
    
    		gamet11.start();
    	} 
    	
    	public void start(){
    		System.out.println("Start Battle"); 
    		startBattle();
    		
    		if(currentPlayer.getLifePoints()>0){
    			System.out.println("You Win!"); 
    		}else{
    			System.out.println("Opponent Wins"); 
    		}
    		
    		System.out.println("Battle Finished"); 
    	}
    	
    	public void startBattle() {
    		while (!player1.isDead() && !player2.isDead()){
    			System.out.println("hi"); 
    			Card currentPlayerRandomCard = currentPlayer.getRandHand();
    			System.out.println(currentPlayerRandomCard.getApc()); 
    			break;
    			
    			 
    			
    			/*if (currentPlayerRandomCard.getApc() == opponentRandomCard.getApc()){
    				startBattle();
    			} else if (currentPlayerRandomCard.getApc() > opponentRandomCard.getApc()) {
    				
    				System.out.println("Player2 LifePoints after deduction= " + opponentPlayer.getLifePoints() +"Lp" + "\n"); 
    			} else {
    				
    			}*/
    		}	
    	}
    Player:
    Java Code:
    public class Player {
        private String name;
        private int lifePoints = 100;
        private Deck deck;
        private Hand hand;
     
        public Player(String name) {
            this.name = name;
    		this.deck = new Deck();								    //Create deck obj for player1/2
            this.deck.addCard(new Card("c1", 20, 100, "fire"));		
            this.deck.addCard(new Card("c2",30, 80, "fire"));		// Using Deck's addCard method to add to arrayList
            this.deck.addCard(new Card("c3",10, 90, "water"));
            this.deck.addCard(new Card("c4",40, 100, "grass"));
            this.deck.addCard(new Card("c5",50, 80, "fire"));
            this.deck.addCard(new Card("c6",60, 90, "water"));
            this.deck.addCard(new Card("c7",20, 90, "fire"));
            this.deck.addCard(new Card("c8",30, 90, "fire"));
            this.deck.addCard(new Card("c9",10, 90, "water"));
            this.deck.addCard(new Card("c10",30, 90, "grass"));
            this.deck.addCard(new Card("c11",40, 100, "grass"));
            this.deck.addCard(new Card("c12",50, 80, "fire"));
            this.deck.addCard(new Card("c13",60, 90, "water"));
            this.deck.addCard(new Card("c14",20, 90, "fire"));
            this.deck.addCard(new Card("c15",30, 90, "fire"));
        }
     
        public String getName() {
        	return name;
        }
        
        public int getLifePoints(){
        	return lifePoints;    	
        }
        
        public void setLifePoints(int lifePoints){
        	this.lifePoints = lifePoints;
        }
        
        public boolean isDead(){
        	return getLifePoints() < 0;
        }
        public Card getRandHand(){
        	return this.hand.getRandomCardInHandmethod();
        }
    }
    Deck:
    [CODE]
    Java Code:
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
     
    public class Deck {
    	private List<Card> cards;
    
        public Deck() {
            this.cards = new ArrayList<>(); 
        }
    
        public void addCard(Card card) {
            this.cards.add(card);           
        }
    
        public List<Card> getCards(final int amount) {
            ArrayList<Card> result = new ArrayList<>();
            Random random = new Random();
            for (int i = 0; i < amount; i++) {
                int randomIndex = random.nextInt(cards.size()); 
                result.add(cards.remove(randomIndex));
            }
            return result;
        }
    }
    Hand:
    Java Code:
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    
    public class Hand {
        private final Deck deck;
        private final int cardsAmount;
        private List<Card> cardsInHand;
    
        public Hand(Deck deck, int cardsAmount) {
             this.deck = deck;
             this.cardsInHand = new ArrayList<>();  
             this.cardsAmount = cardsAmount;
        }
    
        public List<Card> cards() {
            if(cardsInHand == null) cardsInHand = deck.getCards(cardsAmount);
            return cardsInHand;
        }
        
        public int gethand(Card cards) {
        	  return cardsInHand.indexOf(cards);
        }
        
        public Card getRandomCardInHandmethod() {
            int randomIndex = new Random().nextInt(this.cardsInHand.size()); 
            return cardsInHand.get(randomIndex);		
        }
    }
    In one of your earlier posts you suggested not to pull in 5 card objects from the deck ArrayList. I did try that way since nothing was working out and it was incredible inefficient with the amount of code that needed to be written and became so complicated and it never worked out.
    Last edited by Kanada; 01-05-2018 at 04:52 PM.

  14. #14
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,964
    Rep Power
    7

    Default Re: How to write a method within a method?

    Pay close attention of what I type. Stop assuming. The poker game was an example to get a point across about approaching Object Oriented Programming, as we do in Java. I never said you should have a Bank class. Since card games are all alike, but with different rules, it probably has some common areas in your game. That's why I chose Poker, for easy recognition.

    You seem to be sprinkling all sorts of fields through your classes because it doesn't work. However, by doing that, you make it even more hard to see what's really happening.

    Let's focus first on the classes, and do the startBattle last. We already identified Game, Player, Deck, Hand, Card. This looks pretty solid already.

    Now, for the fields, which classes need what fields? If we go by the "has-a" rule, then
    - a Game has a Deck
    - a Game has Players
    - a Deck has Cards
    - a Player has a Hand
    - a Hand has Cards.

    In your code I don't think you need:
    - The Hand field in Game: A Game does not have a Hand, only Players have one
    - The Deck field in Hand: This is only necessary if the Hand needs to take cards from the Deck itself. At this point I would choose to have the Game hand out the cards to the Players.
    - The Deck field in Player: See reason above.

    If you want your Game to be able to access the player's Hand, you should make a get-method for it (aptly called a "getter"). So don't go passing all sorts of Hand objects around, just grab the one you need from the object that has it:
    Java Code:
    Player player1 = new Player();
    Hand hand1 = player1.getHand();
    Card card1 = hand1.getRandomCard();
    I've created a few classes that demonstrate this. Don't blindly delete your old code and use this, because I haven't got all the logic you got in there. See if you understand how Game accesses the Players's Hand by calling the getHand() method and operate on that.

    Java Code:
    public class Game {
        private Player player1;
        private Player player2;
        private Deck deck;
    
        public Game() {
        }
    
        public static void main(String[] args) {
            Game game = new Game();
            game.start();
        }
    
        private void start() {
            deck = new Deck();
            player1 = new Player("John");
            player2 = new Player("Jane");
    
            Hand handOfPlayer1 = player1.getHand();
            handOfPlayer1.addCards(deck.getCards(5));
    
            Hand handOfPayer2 = player2.getHand();
            handOfPayer2.addCards(deck.getCards(5));
    
            startBattle();
        }
    
        public void startBattle() {
            while (!player1.isDead() && !player2.isDead()) {
                System.out.println("NEW ROUND!");
                Hand player1Hand = player1.getHand();
                Card card1 = player1Hand.getRandomCard();
    
                Hand player2Hand = player2.getHand();
                Card card2 = player2Hand.getRandomCard();
    
                System.out.printf("Player %s pulled card %s with APC %s and has %s cards left%n", player1.getName(), card1.getName(), card1.getApc(), player1Hand.getNumberOfCardsLeft());
                System.out.printf("Player %s pulled card %s with APC %s and has %s cards left%n", player2.getName(), card2.getName(), card2.getApc(), player2Hand.getNumberOfCardsLeft());
    
                if (card1.getApc() > card2.getApc()) {
                    //card 1 wins
                    player2.setLifePoints(player2.getLifePoints() - card1.getApc());
                }
                else if (card1.getApc() > card2.getApc()) {
                    //card 2 wins
                    player1.setLifePoints(player1.getLifePoints() - card2.getApc());
                }
    
                System.out.printf("Player 1 has %s life points left%n", player1.getLifePoints());
                System.out.printf("Player 2 has %s life points left%n", player2.getLifePoints());
            }
    
            if (player1.isDead()) {
                System.out.println("Player 2 wins");
            }
            else if (player2.isDead()) {
                System.out.println("Player 1 wins");
            }
    
        }
    
    }
    Java Code:
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    
    public class Deck {
        List<Card> cards;
    
        public Deck() {
            cards = new ArrayList<>();
    
            addCard(new Card("c1", 20, 100, "fire"));
            addCard(new Card("c2", 30, 80, "fire"));
            addCard(new Card("c3", 10, 90, "water"));
            addCard(new Card("c4", 40, 100, "grass"));
            addCard(new Card("c5", 50, 80, "fire"));
            addCard(new Card("c6", 60, 90, "water"));
            addCard(new Card("c7", 20, 90, "fire"));
            addCard(new Card("c8", 30, 90, "fire"));
            addCard(new Card("c9", 10, 90, "water"));
            addCard(new Card("c10", 30, 90, "grass"));
            addCard(new Card("c11", 40, 100, "grass"));
            addCard(new Card("c12", 50, 80, "fire"));
            addCard(new Card("c13", 60, 90, "water"));
            addCard(new Card("c14", 20, 90, "fire"));
            addCard(new Card("c15", 30, 90, "fire"));
        }
    
        public void addCard(Card card) {
            this.cards.add(card);
        }
    
        public List<Card> getCards(int number) {
            List<Card> result = new ArrayList<>();
            Random random = new Random();
            for (int i = 0; i < number; i++) {
                int randomIndex = random.nextInt(cards.size());
                result.add(cards.remove(randomIndex));
            }
            return result;
        }
    }
    Java Code:
    public class Player {
        private String name;
        private int lifePoints = 100;
    
        private Hand hand;
    
        public Player(String name) {
            this.name = name;
            this.hand = new Hand();
        }
    
        public Hand getHand() {
            return hand;
        }
    
        public String getName() {
            return name;
        }
    
        public int getLifePoints() {
            return lifePoints;
        }
    
        public void setLifePoints(int lifePoints) {
            this.lifePoints = lifePoints;
        }
    
        public boolean isDead() {
            return lifePoints <= 0;
        }
    }
    Java Code:
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    
    public class Hand {
        private List<Card> cards;
    
        public Hand() {
            this.cards = new ArrayList<>();
        }
    
        public Card getRandomCard() {
            int randomIndex = new Random().nextInt(this.cards.size());
            return cards.remove(randomIndex);
        }
    
        public void addCard(Card card) {
            //method for adding just one card
            this.cards.add(card);
        }
    
        public void addCards(List<Card> cards) {
            //method for adding a bunch of cards at once
            this.cards.addAll(cards);
        }
    
        public int getNumberOfCardsLeft() {
            return cards.size();
        }
    }
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  15. #15
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,964
    Rep Power
    7

    Default Re: How to write a method within a method?

    And another quick tip: try not to post "it doesn't work". Try to describe what's the input, what's the output, the expected output, any errors or stacktraces if available. Understanding how to read a stacktrace is important. We can help with that too.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  16. #16
    Kanada is offline Member
    Join Date
    Mar 2017
    Posts
    14
    Rep Power
    0

    Default Re: How to write a method within a method?

    I sorted out my deck and hand array after many hours of getting a simple working structure and have finally got it successfully integrated into my game loop.

    So I got something solid down and the game runs but there's something in the game loop that I want to stop from being repeated.

    So heres what's going on in my startbattle().
    1.Start battle loops until player one or 2 is dead
    2.I get my lifepoints for both players.
    3.I get 5 random cards from my deck arraylist
    4.I add those 5 random cards from player1/2 deck arrayList to their hand arrayList
    5.I get a random card out of the 5cards in their hand arraylist and this is the card to be used in my if/else game loop
    6.I do all that deducting of players lifepoints, I remove that used card away from both the deck arrayList and the hand arrayList of both players. So this card is what I call in the graveyard using card game terms.
    7.Here's the problem, after the if/else battling ends it goes up to step 1 again and so it adds 5 more random cards to the deck and hand arrayList which I don't want because now the hand arrayList has 9 cards and also the deck arrayList could have the card that's in the graveyard come back and be added into the deck again.

    One solution is to limit the size of the hand array. Lets say to limit the hand arrayList to 5 cards. There's various problems to this, mainly the hand limiting factor of 5 cards. Future developments in the game is that you might get a cards with abilities that allows you to draw more cards to your hand so it will go above the 5 card limit. This method might solve my problem now but it won't work in the longterm.

    I figured the idea out for the 2nd method but don't know how to do it. First add every single card from my player class to each player's respective decks (this bit I know how to do when I go back to rewrite my code). At the end of the first run it will repeat (until a player loses all the lifepoint) but instead of step 4 again (which is to add 5 more cards to the hand arrayList), step 4 now becomes just add one card from deck to the hand arrayList. Is there any good way to stop it from looping to that point and having this new condition replacing that part of the loop instead in startBattle()?

    Game13 class:
    Java Code:
    import java.util.Random;
    
    public class Game13 {
    	public Game13 gamet13;
    	private Player player1;
    	private Player player2;
    	private Player currentPlayer;
    	private Player opponentPlayer;
    	private Deck deck;
    	private Hand hand;
    	
    	public static void main(String[] args) {	
    		Player player1 = new Player("Player 1"); //Inputs "Player 1" as name into class Player
    		Player player2 = new Player("Player 2");
    		/*System.out.println(player1.getName()); //gets name from class Player getName();
    		System.out.println(player2.getName());  */
    
    		Game13 gamet13 = new Game13(player1, player2);
    		gamet13.setCurrentPlayer(player1);
    		gamet13.setOpponentPlayer(player2);
    
    		gamet13.start();
    	} 
    	
    	public void start(){
    		System.out.println("Start Battle"); 
    		startBattle();
    		
    		if(currentPlayer.getLifePoints()>0){
    			System.out.println("You Win!"); 
    		}else{
    			System.out.println("Opponent Wins"); 
    		}
    		
    		System.out.println("Battle Finished"); 
    	}
    	
    	public void startBattle() {
    		while (!player1.isDead() && !player2.isDead()){
    			//What to get here when startBattle() activates?
    			//Player object grab random card object from hand arraylist
    			//grab card from deck
    			
    			//Player gets their lifepoints
    			int currentPlayerLifePoints = currentPlayer.getLifePoints();
    			int opponentPlayerLifePoints = opponentPlayer.getLifePoints();
    			
    			//Current player gets adds 5 random cards to their deck
    			Card currentPlayerRandDeckCard1 = currentPlayer.getRandDeckCard(); 
    			Card currentPlayerRandDeckCard2 = currentPlayer.getRandDeckCard(); 
    			Card currentPlayerRandDeckCard3 = currentPlayer.getRandDeckCard(); 
    			Card currentPlayerRandDeckCard4 = currentPlayer.getRandDeckCard(); 
    			Card currentPlayerRandDeckCard5 = currentPlayer.getRandDeckCard(); 
    			
    			//Player adds those 5 cards from their deck arrayList to their hand arraylist
    			currentPlayer.addToHandArray(currentPlayerRandDeckCard1);
    			currentPlayer.addToHandArray(currentPlayerRandDeckCard2);
    			currentPlayer.addToHandArray(currentPlayerRandDeckCard3);
    			currentPlayer.addToHandArray(currentPlayerRandDeckCard4);
    			currentPlayer.addToHandArray(currentPlayerRandDeckCard5);
    			
    			Card oppPlayerRandDeckCard1 = opponentPlayer.getRandDeckCard(); 
    			Card oppPlayerRandDeckCard2 = opponentPlayer.getRandDeckCard(); 
    			Card oppPlayerRandDeckCard3 = opponentPlayer.getRandDeckCard(); 
    			Card oppPlayerRandDeckCard4 = opponentPlayer.getRandDeckCard(); 
    			Card oppPlayerRandDeckCard5 = opponentPlayer.getRandDeckCard(); 
    
    			opponentPlayer.addToHandArray(oppPlayerRandDeckCard1);
    			opponentPlayer.addToHandArray(oppPlayerRandDeckCard2);
    			opponentPlayer.addToHandArray(oppPlayerRandDeckCard3);
    			opponentPlayer.addToHandArray(oppPlayerRandDeckCard4);
    			opponentPlayer.addToHandArray(oppPlayerRandDeckCard5);
    			
    			//Players gets a random card from their hand arraylist
    			Card currentPlayerRandHandCard = currentPlayer.getRandHandCard(); //grab card from handarray
    			Card oppPlayerRandHandCard = opponentPlayer.getRandHandCard(); //grab card from handarray
    			
    			if (currentPlayerRandHandCard.getApc() == oppPlayerRandHandCard.getApc()){
    				startBattle();
    				
    			} else if (currentPlayerRandHandCard.getApc() > oppPlayerRandHandCard.getApc()) {
    				System.out.println("You Win the round!" + "\n" ); 
    				System.out.println("Ply1="+currentPlayerRandHandCard.getCardId() +" "+ "Ply2=" + oppPlayerRandHandCard.getCardId()); 
    				//Deducting lifepoints condition
    				int diff = currentPlayerRandHandCard.getApc() - oppPlayerRandHandCard.getApc();
    				System.out.println("Difference in Apc = " + diff); 							//Difference in Apc will be deducted from loser's LifePoints
    				opponentPlayer.setLifePoints(opponentPlayerLifePoints - diff);
    				System.out.println("Player2 LifePoints after deduction= " + opponentPlayer.getLifePoints() +"Lp" + "\n"); 
    				//remove currentplayer hand array card
    				currentPlayer.removeHandArrayCard(currentPlayerRandHandCard);
    				opponentPlayer.removeHandArrayCard(oppPlayerRandHandCard);
    				//Check Size of hand
    				currentPlayer.CheckArraySize();
    				
    			} else {
    				System.out.println("Opponent Wins the round!" + "\n");  
    				System.out.println("Ply1="+currentPlayerRandHandCard.getCardId() +" "+ "Ply2=" + oppPlayerRandHandCard.getCardId()); 
    				int diff = oppPlayerRandHandCard.getApc() - currentPlayerRandHandCard.getApc();
    				System.out.println("Difference in Apc = " + diff);
    				currentPlayer.setLifePoints(currentPlayerLifePoints - diff);
    				System.out.println("Player1 LifePoints after deduction=" + currentPlayer.getLifePoints() +"Lp"+  "\n");
    				//remove currentplayer hand array card
    				currentPlayer.removeHandArrayCard(currentPlayerRandHandCard);
    				opponentPlayer.removeHandArrayCard(oppPlayerRandHandCard);
    				//Check Size of hand
    				currentPlayer.CheckArraySize();
    			}
    		}	
    	}
    	
    	public Game13(Player player1, Player player2) {
    		this.player1 = player1;
    	    this.player2 = player2;
    	}
    	
    	public void setCurrentPlayer(Player currentPlayer) {
    		this.currentPlayer = currentPlayer;	//used in psvm to set player 
    	}
    	
    	public Player setOpponentPlayer(Player opponentPlayer){
    		return this.opponentPlayer = opponentPlayer;
    	}
    	
    	public void startGameLoop(){
    		
    	}
    
    }
    Java Code:
    Player class:
    public class Player {
        private String name;
        private int lifePoints = 100;
        private Deck deck;
        private Hand hand;
     
        public Player(String name) {
            this.name = name;
            this.hand = new Hand();
    		this.deck = new Deck();								   
            this.deck.addCard(new Card("c1", 20, 100, "fire"));		
            this.deck.addCard(new Card("c2",30, 80, "fire"));	
            this.deck.addCard(new Card("c3",10, 90, "water"));
            this.deck.addCard(new Card("c4",40, 100, "grass"));
            this.deck.addCard(new Card("c5",50, 80, "fire"));
            this.deck.addCard(new Card("c6",60, 90, "water"));
            this.deck.addCard(new Card("c7",20, 90, "fire"));
            this.deck.addCard(new Card("c8",30, 90, "fire"));
            this.deck.addCard(new Card("c9",10, 90, "water"));
            this.deck.addCard(new Card("c10",30, 90, "grass"));
            this.deck.addCard(new Card("c11",40, 100, "grass"));
            this.deck.addCard(new Card("c12",50, 80, "fire"));
            this.deck.addCard(new Card("c13",60, 90, "water"));
            this.deck.addCard(new Card("c14",20, 90, "fire"));
            this.deck.addCard(new Card("c15",30, 90, "fire"));
        }
     
        public String getName() {
        	return name;
        }
        
        public int getLifePoints(){
        	return lifePoints;    	
        }
        
        public void setLifePoints(int lifePoints){
        	this.lifePoints = lifePoints;
        }
        
        public boolean isDead(){
        	return getLifePoints() < 0;
        }
        
        public Card getRandDeckCard(){
        	return this.deck.getDeckRandomCard();
        }
        
        public void addToHandArray(Card card){
        	this.hand.addHandCard(card);
        }
    
        public Card getRandHandCard(){
        	return this.hand.getHandRandomCard();
        }
        
        public void removeHandArrayCard(Card card){
        	this.hand.addHandCard(card);
        }
        
        public void CheckArraySize(){
        	this.hand.CheckArraySize();
        }
        
    }

    Deck Class:
    Java Code:
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
     
    public class Deck {
    	private List<Card> cards;
    
        public Deck() {
            this.cards = new ArrayList<>(); 	 // ply1/2 created deck object and each deck object creates cards arrayList in public Player (String name){}1
        }
    
        public void addCard(Card card) {
            this.cards.add(card);           
        }
    
        public Card getDeckRandomCard(){
        	int randomIndex = new Random().nextInt(this.cards.size()); //List called cards
            return cards.get(randomIndex);      //Random().nextInt gets a random element in cards?
        }
    }

    Hand Class:
    Java Code:
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    
    public class Hand {
    	private List<Card> handCards;
    	
    	public Hand(){
    		this.handCards = new ArrayList<>();
    	}
    	
    	public void addHandCard(Card card){
    		this.handCards.add(card);
    	}
    	
    	public Card getHandRandomCard(){
    	    	int randomIndex = new Random().nextInt(this.handCards.size()); //List called cards
    	        return handCards.get(randomIndex);      //Random().nextInt gets a random element in cards?
    	}
    	
    	public void removeCard(Card card) {
    	     this.handCards.remove(card);
    	}
    	
    	public void CheckArraySize(){
    		System.out.println("Cards in hand= " + this.handCards.size()); 
    	}
    }

  17. #17
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,964
    Rep Power
    7

    Default Re: How to write a method within a method?

    Are the players supposed to battle it out with 5 cards? I.e. I get 5 cards, you get 5 cards, and then we battle until it's over? In that case, you should move the handing out of the cards OUT of the loop. From your descrption, it looks like the loop should start between item #4 and #5. I copied the description you gave and moved the loop to #4. Is that how it works?

    1.I get my lifepoints for both players.
    2.I get 5 random cards from my deck arraylist
    3.I add those 5 random cards from player1/2 deck arrayList to their hand arrayList
    4.Start battle loops until player one or 2 is dead
    5.I get a random card out of the 5cards in their hand arraylist and this is the card to be used in my if/else game loop
    6.I do all that deducting of players lifepoints, I remove that used card away from both the deck arrayList and the hand arrayList of both players. So this card is what I call in the graveyard using card game terms.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  18. #18
    Kanada is offline Member
    Join Date
    Mar 2017
    Posts
    14
    Rep Power
    0

    Default Re: How to write a method within a method?

    I tried to move the handing of cards out of the loop but when the next method runs, it can't because the variable scope is out of its method boundaries and can't call it?

    I just got a idea right here. Maybe the player class should initiate 5 cards somehow for the start. I feel like this brings about future development problems and thought processes though because my coding thinking process is what happens as if I'm playing in real life where the drawing of cards must work in the game class rather than cheating by initializing before anything happens. It's hard to tell with these things since I don't have coding experience.

    Okay, back to the topic. My game is as you described but I'll write it a bit more in depth in the game logic:
    1.Both players have a deck of cards. I'm giving them 35 cards each at the moment.
    2.Both players have lifepoints of 200LP.
    3.Each card has been given properties. AT the moment the only one I'm using is APC (attack points)

    So they when they are in game:
    4.Both players draw 5 cards from their deck.
    5.Both place a card down at the same time (at the moment there're no turns)
    6.Whoever has the higher APC wins the round.
    7.The difference between the APC of the 2 cards played is calculated. winnerAPC -loserAPC. This value is deducted from loser's lifepoints.
    8.If both APC's are the same then it's a draw and nothing happens.
    9.players draw 1 new card to their hand from their respective decks and so the battle cycle repeats.

    So the problem before, I had the trouble of the loop repeating to the part adding 5 cards to the hand over and over again. I stopped it by inputting a turn counter where:
    if (turn==0){add 5 cards to hand, turn++, do battling}
    else(turn>=1){add 1 card to hand, turn++, do battling}

    This way of doing is kind of clumbersome as I have to copy and paste the long lines of code of do battling twice.
    This isn't really a huge problem since the code does run. The problem is that within that battling code is the first conditions of it.
    Right now it:

    if(apc1=apc2){
    startbattle());
    }
    elseif(apc1>apc2){
    battling code
    }
    else{
    battling code
    }

    The problem is that when it's a draw, no cards get discarded and so when it loops back to a top. A extra card gets added to the hand. I would have probably preferred your suggestion since there's another problem that sprouted out with turn counters. There's probably a way to restrict hand arrayList to 5 cards to prevent it from adding like crazy that's happening right now with the drawing condition. I don't want this because in the future a card could have abilities where you can draw extra cards.

    Is there anyway to stop this over drawing problem right now? It's unfortunate that I ended up with this turn counter method but I couldn't for the life of me figure out how to do your suggestion.

    Java Code:
    public class Game13 {
    	public Game13 gamet13;
    	private Player player1;
    	private Player player2;
    	private Player currentPlayer;
    	private Player opponentPlayer;
    	private static int turn = 0;
    	
    	public static void main(String[] args) {	
    		Player player1 = new Player("Player 1"); //Inputs "Player 1" as name into class Player
    		Player player2 = new Player("Player 2");
    		/*System.out.println(player1.getName()); //gets name from class Player getName();
    		System.out.println(player2.getName());  */
    
    		Game13 gamet13 = new Game13(player1, player2);
    		gamet13.setCurrentPlayer(player1);
    		gamet13.setOpponentPlayer(player2);
    
    		gamet13.start();
    	} 
    	
    	public void start(){
    		System.out.println("Start Battle"); 
    		startBattle();
    		
    		if(currentPlayer.getLifePoints()>0){
    			System.out.println("You Win!"); 
    		}else{
    			System.out.println("Opponent Wins"); 
    		}
    		
    		System.out.println("Battle Finished"); 
    	}
    	
    	public void startBattle() {
    		currentPlayer.getLifePoints();
    		while (!player1.isDead() && !player2.isDead()){
    			gameLoop();
    		}	
    	}
    	
    	public void gameLoop(){
    		//turn counter
    		if (turn==0){
    			//Make turn + 1
    			turn++;
    			System.out.println("Turn = " + turn); 
    			
    			//Player gets their lifepoints
    			int currentPlayerLifePoints = currentPlayer.getLifePoints();
    			int opponentPlayerLifePoints = opponentPlayer.getLifePoints();
    			
    			//Players gets 5 random cards from deck
    			Card currentPlayerRandDeckCard1 = currentPlayer.getRandDeckCard(); 
    			Card currentPlayerRandDeckCard2 = currentPlayer.getRandDeckCard(); 
    			Card currentPlayerRandDeckCard3 = currentPlayer.getRandDeckCard(); 
    			Card currentPlayerRandDeckCard4 = currentPlayer.getRandDeckCard(); 
    			Card currentPlayerRandDeckCard5 = currentPlayer.getRandDeckCard(); 
    			
    			Card oppPlayerRandDeckCard1 = opponentPlayer.getRandDeckCard(); 
    			Card oppPlayerRandDeckCard2 = opponentPlayer.getRandDeckCard(); 
    			Card oppPlayerRandDeckCard3 = opponentPlayer.getRandDeckCard(); 
    			Card oppPlayerRandDeckCard4 = opponentPlayer.getRandDeckCard(); 
    			Card oppPlayerRandDeckCard5 = opponentPlayer.getRandDeckCard(); 
    			
    			//Player adds those 5 cards from their deck arrayList to their hand arraylist
    			currentPlayer.addToHandArray(currentPlayerRandDeckCard1);
    			currentPlayer.addToHandArray(currentPlayerRandDeckCard2);
    			currentPlayer.addToHandArray(currentPlayerRandDeckCard3);
    			currentPlayer.addToHandArray(currentPlayerRandDeckCard4);
    			currentPlayer.addToHandArray(currentPlayerRandDeckCard5);
    			
    			opponentPlayer.addToHandArray(oppPlayerRandDeckCard1);
    			opponentPlayer.addToHandArray(oppPlayerRandDeckCard2);
    			opponentPlayer.addToHandArray(oppPlayerRandDeckCard3);
    			opponentPlayer.addToHandArray(oppPlayerRandDeckCard4);
    			opponentPlayer.addToHandArray(oppPlayerRandDeckCard5);
    			
    			//Remove those loaded cards from Deck Array
    			currentPlayer.removeDeckArrayCard(currentPlayerRandDeckCard1);
    			currentPlayer.removeDeckArrayCard(currentPlayerRandDeckCard2);
    			currentPlayer.removeDeckArrayCard(currentPlayerRandDeckCard3);
    			currentPlayer.removeDeckArrayCard(currentPlayerRandDeckCard4);
    			currentPlayer.removeDeckArrayCard(currentPlayerRandDeckCard5);
    	
    			opponentPlayer.removeDeckArrayCard(oppPlayerRandDeckCard1);
    			opponentPlayer.removeDeckArrayCard(oppPlayerRandDeckCard2);
    			opponentPlayer.removeDeckArrayCard(oppPlayerRandDeckCard3);
    			opponentPlayer.removeDeckArrayCard(oppPlayerRandDeckCard4);
    			opponentPlayer.removeDeckArrayCard(oppPlayerRandDeckCard5);
    			
    			//Players gets a random card from their hand arraylist
    			Card currentPlayerRandHandCard = currentPlayer.getRandHandCard(); //grab card from handarray
    			Card oppPlayerRandHandCard = opponentPlayer.getRandHandCard(); //grab card from handarray
    			
    			if (currentPlayerRandHandCard.getApc() == oppPlayerRandHandCard.getApc()){
    				System.out.println("It's a draw! Draw a card from hand again." + "\n"); 
    				startBattle();
    				
    			} else if (currentPlayerRandHandCard.getApc() > oppPlayerRandHandCard.getApc()) {
    				System.out.println("You Win the round!" + "\n" ); 
    				System.out.println("Ply1="+currentPlayerRandHandCard.getCardId() +" "+ "Ply2=" + oppPlayerRandHandCard.getCardId()); 
    				//Deducting lifepoints condition
    				int diff = currentPlayerRandHandCard.getApc() - oppPlayerRandHandCard.getApc();
    				System.out.println("Difference in Apc = " + diff); 							//Difference in Apc will be deducted from loser's LifePoints
    				opponentPlayer.setLifePoints(opponentPlayerLifePoints - diff);
    				System.out.println("opponentPlayer LifePoints after deduction= " + opponentPlayer.getLifePoints() +"Lp" + "\n"); 
    				//remove currentPlayer/opponentPlayer hand array card
    				currentPlayer.removeHandArrayCard(currentPlayerRandHandCard);
    				opponentPlayer.removeHandArrayCard(oppPlayerRandHandCard);
    				//Check Size of hand and deck of currentPlayer
    				currentPlayer.checkHandArraySize();
    				currentPlayer.checkDeckArraySize();
    				//print LP of players
    				System.out.println("currentPlayer LP = " + currentPlayer.getLifePoints()); 
    				System.out.println("opponentPlayer LP = " + opponentPlayer.getLifePoints()); 
    				
    			} else {
    				System.out.println("Opponent Wins the round!" + "\n");  
    				System.out.println("Ply1="+currentPlayerRandHandCard.getCardId() +" "+ "Ply2=" + oppPlayerRandHandCard.getCardId()); 
    				int diff = oppPlayerRandHandCard.getApc() - currentPlayerRandHandCard.getApc();
    				System.out.println("Difference in Apc = " + diff);
    				currentPlayer.setLifePoints(currentPlayerLifePoints - diff);
    				System.out.println("Player1 LifePoints after deduction=" + currentPlayer.getLifePoints() +"Lp"+  "\n");
    				//remove currentPlayer/opponentPlayer hand array card
    				currentPlayer.removeHandArrayCard(currentPlayerRandHandCard);
    				opponentPlayer.removeHandArrayCard(oppPlayerRandHandCard);
    				//Check Size of hand
    				currentPlayer.checkHandArraySize();
    				currentPlayer.checkDeckArraySize();
    				//print LP of players
    				System.out.println("currentPlayer LP = " + currentPlayer.getLifePoints()); 
    				System.out.println("opponentPlayer LP = " + opponentPlayer.getLifePoints() ); 
    			}
    			
    		} else {
    				turn++;
    				System.out.println("Turn = " + turn); 
    			
    				int currentPlayerLifePoints = currentPlayer.getLifePoints();
    				int opponentPlayerLifePoints = opponentPlayer.getLifePoints();
    				
    				//Players gets 1 random cards from deck. I.e. draw one card from deck
    				Card currentPlayerRandDeckCard1 = currentPlayer.getRandDeckCard(); 
    				Card oppPlayerRandDeckCard1 = opponentPlayer.getRandDeckCard(); 
    				
    				//Player adds those 5 cards from their deck arrayList to their hand arraylist
    				currentPlayer.addToHandArray(currentPlayerRandDeckCard1);
    				opponentPlayer.addToHandArray(oppPlayerRandDeckCard1);
    				
    				//Remove those loaded cards from Deck Array
    				currentPlayer.removeDeckArrayCard(currentPlayerRandDeckCard1);
    				opponentPlayer.removeDeckArrayCard(oppPlayerRandDeckCard1);
    				
    				//Players gets a random card from their hand arraylist
    				Card currentPlayerRandHandCard = currentPlayer.getRandHandCard(); //grab card from handarray
    				Card oppPlayerRandHandCard = opponentPlayer.getRandHandCard(); //grab card from handarray
    				
    				if (currentPlayerRandHandCard.getApc() == oppPlayerRandHandCard.getApc() && turn >= 1){
    					System.out.println("It's a draw! Draw a card from hand again." + "\n"); 
    					gameLoop();
    					
    				} else if (currentPlayerRandHandCard.getApc() > oppPlayerRandHandCard.getApc()) {
    					System.out.println("You Win the round!" + "\n" ); 
    					System.out.println("Ply1="+currentPlayerRandHandCard.getCardId() +" "+ "Ply2=" + oppPlayerRandHandCard.getCardId()); 
    					//Deducting lifepoints condition
    					int diff = currentPlayerRandHandCard.getApc() - oppPlayerRandHandCard.getApc();
    					System.out.println("Difference in Apc = " + diff); 							//Difference in Apc will be deducted from loser's LifePoints
    					opponentPlayer.setLifePoints(opponentPlayerLifePoints - diff);
    					System.out.println("opponentPlayer LifePoints after deduction= " + opponentPlayer.getLifePoints() +"Lp" + "\n"); 
    					//remove currentPlayer/opponentPlayer hand array card
    					currentPlayer.removeHandArrayCard(currentPlayerRandHandCard);
    					opponentPlayer.removeHandArrayCard(oppPlayerRandHandCard);
    					//Check Size of hand and deck of currentPlayer
    					currentPlayer.checkHandArraySize();
    					currentPlayer.checkDeckArraySize();
    					//print LP of players
    					System.out.println("currentPlayer LP = " + currentPlayer.getLifePoints()); 
    					System.out.println("opponentPlayer LP = " + opponentPlayer.getLifePoints()); 
    					
    				} else {
    					System.out.println("Opponent Wins the round!" + "\n");  
    					System.out.println("Ply1="+currentPlayerRandHandCard.getCardId() +" "+ "Ply2=" + oppPlayerRandHandCard.getCardId()); 
    					int diff = oppPlayerRandHandCard.getApc() - currentPlayerRandHandCard.getApc();
    					System.out.println("Difference in Apc = " + diff);
    					currentPlayer.setLifePoints(currentPlayerLifePoints - diff);
    					System.out.println("currentPlayer LifePoints after deduction=" + currentPlayer.getLifePoints() +"Lp"+  "\n");
    					//remove currentPlayer/opponentPlayer hand array card
    					currentPlayer.removeHandArrayCard(currentPlayerRandHandCard);
    					opponentPlayer.removeHandArrayCard(oppPlayerRandHandCard);
    					//Check Size of hand
    					currentPlayer.checkHandArraySize();
    					currentPlayer.checkDeckArraySize();
    					//print LP of players
    					System.out.println("currentPlayer LP = " + currentPlayer.getLifePoints()); 
    					System.out.println("opponentPlayer LP = " + opponentPlayer.getLifePoints()); 
    			}
    		}
    	}
    	
    	public Game13(Player player1, Player player2) {
    		this.player1 = player1;
    	    this.player2 = player2;
    	    
    	}
    	
    	public void setCurrentPlayer(Player currentPlayer) {
    		this.currentPlayer = currentPlayer;	//used in psvm to set player 
    	}
    	
    	public Player setOpponentPlayer(Player opponentPlayer){
    		return this.opponentPlayer = opponentPlayer;
    	}
    }

  19. #19
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,964
    Rep Power
    7

    Default Re: How to write a method within a method?

    The reason this game has become so complex is that you seem to think that you need to keep a hold of ALL the objects you create. That is not necessary. You don't need to create new cards and hold on to each and every one of them. The only thing you need is the Player object and work your way from there. All following actions are done on the player and its properties: Player -> Hand -> Card

    So if you need a Card from the Player, you first get the Hand, then ask the Hand for a Card. You can either write that in two lines:
    Java Code:
    Hand hand = player.getHand();
    Card = hand.getRandomCard();
    Or do it in one line:
    Java Code:
    Card card = player.getHand().getRandomCard();
    I have created a minimal working game. Pay close attention as to how cards are added to and retrieved from the Hands via the Player objects. As you can see there is no hundreds of references to cards being used in the game. At game start I grab 5 Cards from the Deck and add them to the Hand of each player. After that, during the game loop, I just pick one from the Hand object and use that.

    The only repetition here is the filling of the Deck with cards when it's created. I just create a handful of identical cards and added them to the Deck. In your case, you would probably have 200 unique cards. (Note the addition of Collections.shuffle() )

    It might help if you scrap what you have now and start over. It sounds like a lot of work down the drain, and while that might be true, it also helps you apply what you have learned so far and not being hindered by the errors you made in the past.

    Game
    Java Code:
    import java.util.List;
    
    public class Game {
        private Player player1;
        private Player player2;
    
        public static void main(String[] args) {
            Game game = new Game();
            game.start();
        }
    
        public Game() {
            this.player1 = new Player("Annie");
            this.player2 = new Player("Bob");
        }
    
        private void start() {
            Deck deck = new Deck();
    
            List<Card> randomCardsForPlayer1 = deck.getRandomCards(5);
            Hand handOfPLayer1 = player1.getHand();
            handOfPLayer1.addAllCards(randomCardsForPlayer1);
    
            List<Card> randomCardsForPlayer2 = deck.getRandomCards(5);
            Hand handForPlayer2 = player2.getHand();
            handForPlayer2.addAllCards(randomCardsForPlayer2);
    
            startBattle();
        }
    
        private void startBattle() {
            while (!player1.isDead() && !player2.isDead()) {
                Card card1 = player1.getHand().getRandomCard();
                Card card2 = player2.getHand().getRandomCard();
    
                System.out.println("Player " + player1.getName() + " drew " + card1.getApc());
                System.out.println("Player " + player2.getName() + " drew " + card2.getApc());
    
                if (card1.getApc() > card2.getApc()) {
                    System.out.println("Player " + player1.getName() + " wins with " + card1.getApc() + " over " + card2.getApc());
                    player2.setHealthPoints(player2.getHealthPoints() - card1.getApc());
                    System.out.println("Player " + player2.getName() + " has " + player2.getHealthPoints() + " left");
                }
                else if (card2.getApc() > card1.getApc()) {
                    System.out.println("Player " + player2.getName() + " wins with " + card2.getApc() + " over " + card1.getApc());
                    player1.setHealthPoints(player1.getHealthPoints() - card2.getApc());
                    System.out.println("Player " + player1.getName() + " has " + player1.getHealthPoints() + " left");
                }
                else {
                    System.out.println("It's a draw!");
                }
    
            }
        }
    }
    Player
    Java Code:
    public class Player {
        private String name;
        private Hand hand;
        private int healthPoints;
    
        public Player(String name) {
            this.name = name;
            this.hand = new Hand();
            this.healthPoints = 100;
        }
    
        public String getName() {
            return name;
        }
    
        public Hand getHand() {
            return hand;
        }
    
        public int getHealthPoints() {
            return healthPoints;
        }
    
        public void setHealthPoints(int healthPoints) {
            this.healthPoints = healthPoints;
        }
    
        public boolean isDead() {
            return healthPoints <= 0;
        }
    }
    Hand
    Java Code:
    import java.util.*;
    
    public class Hand {
        private List<Card> cards;
    
        public Hand() {
            cards = new ArrayList<>();
        }
    
        public void addCard(Card card) {
            cards.add(card);
        }
    
        public void addAllCards(List<Card> cards) {
            this.cards.addAll(cards);
        }
    
        public Card getRandomCard() {
            int rand = new Random().nextInt(cards.size());
            return this.cards.remove(rand);
        }
    
    }
    Deck
    Java Code:
    import java.util.*;
    
    public class Deck {
        private List<Card> cards;
    
        public Deck() {
            cards = new ArrayList<>();
            cards.add(new Card(10));
            cards.add(new Card(10));
            cards.add(new Card(10));
            cards.add(new Card(10));
            cards.add(new Card(10));
    
            cards.add(new Card(20));
            cards.add(new Card(20));
            cards.add(new Card(20));
            cards.add(new Card(20));
            cards.add(new Card(20));
    
            cards.add(new Card(30));
            cards.add(new Card(30));
            cards.add(new Card(30));
            cards.add(new Card(30));
            cards.add(new Card(30));
    
            cards.add(new Card(40));
            cards.add(new Card(40));
            cards.add(new Card(40));
            cards.add(new Card(40));
            cards.add(new Card(40));
            
            cards.add(new Card(50));
            cards.add(new Card(50));
            cards.add(new Card(50));
            cards.add(new Card(50));
            cards.add(new Card(50));
    
            Collections.shuffle(cards);
        }
    
        public List<Card> getRandomCards(int number) {
            List<Card>  result = new ArrayList<>();
            for (int i = 0 ; i < number && i < cards.size(); i++) {
                result.add(cards.remove(i));
            }
            return result;
        }
    }
    Card
    Java Code:
    public class Card {
        private int apc;
    
        public Card(int apc) {
            this.apc = apc;
        }
    
        public int getApc() {
            return apc;
        }
    }
    Last edited by SurfMan; 01-10-2018 at 03:04 PM.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  20. #20
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,189
    Rep Power
    12

    Default Re: How to write a method within a method?

    Sorry about jumping in here at the 11th hour but I have noticed that you do not take advantage of the mechanics of the language to
    simplify initializations. This has nothing to do with the game logic but with class and value management. I have re-written the Deck class as
    an example:

    Java Code:
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    
    public class DeckDemo {
       public static void main(String[] args) {
          Deck d = new Deck();
          while (!d.isEmpty()) {
             System.out.println("deck: " + d);
             List<Card> c = d.getRandomCards(3);
             System.out.println("selection: " + c);
          }
       }
    }
    
    
    class Deck {
       private List<Card> cards;
    
    
       public Deck() {
          cards = new ArrayList<>();
          int[] values = {
                10, 10, 10, 10, 10, 20, 20, 20, 20, 20, 30, 30, 30, 30, 30, 40, 40,
                40, 40, 40, 50, 50, 50, 50, 50 };
          for (int v : values) {
             cards.add(new Card(v));
          }
    
    
          Collections.shuffle(cards);
       }
    
    
       public boolean isEmpty() {
          return cards.size() <= 0;
       }
       public List<Card> getRandomCards(int number) {
          number = number <= cards.size() ? number : cards.size();
         // since sublist is only a view, make a hard copy.
          List<Card> result = new ArrayList<>(cards.subList(0, number));
          cards.removeAll(result);
          return result;
       }
       public String toString() {
          return cards.toString();
       }
    }
    You could also have used initializer blocks to do this. My way is not necessarily the only or best way. But at a minimum I would advise you to override toString() in your classes. It can facilitate debugging. Note: Surfman may have already pointed some of this out to you as I have not
    carefully read thru the thread.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 7
    Last Post: 04-11-2013, 05:31 AM
  2. How to Write to a File Using a Method
    By Anagha in forum New To Java
    Replies: 7
    Last Post: 04-06-2011, 06:50 AM
  3. Writing a method to write a method?
    By balla in forum New To Java
    Replies: 5
    Last Post: 04-01-2011, 12:05 PM
  4. how to write method syntax ?
    By Bader in forum New To Java
    Replies: 2
    Last Post: 03-14-2010, 05:58 PM
  5. Trying to write toString method
    By curious in forum New To Java
    Replies: 3
    Last Post: 10-28-2009, 02:43 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •