MentalFloss's Profile User Rating: *****

Reputation: 573 Enlightened
Group:
Author w/DIC++
Active Posts:
1,499 (0.62 per day)
Joined:
02-September 09
Profile Views:
29,428
Last Active:
User is offline Yesterday, 11:02 PM
Currently:
Offline

Previous Fields

Country:
Who Cares
OS Preference:
Who Cares
Favorite Browser:
Who Cares
Favorite Processor:
Who Cares
Favorite Gaming Platform:
Who Cares
Your Car:
Who Cares
Dream Kudos:
250

Latest Visitors

Icon   MentalFloss has not set their status

Posts I've Made

  1. In Topic: How can I improve this code? Text Based Game

    Posted 1 May 2016

    I would create a class called Stat or Range or something that would model a value with a min,max,current value, which can be decremented, incremented, set to max, set to min, stuff like that.

    import java.util.*;
    
    public class Stat
    {
        private int min;
        private int max;
        private int value;
        private static Random r = new Random();
    
        public Stat(int min, int max)
        {
            this(min, max, min);
        }
    
        public Stat(int min, int max, int value)
        {
            this.min = min;
            this.max = max;
            this.value = value;
        }
    
        // getters and setters (which you are now familiar with how to do
    
        // but now we have a special setting behavior as well:
        public void setRandomValue()
        {
            this.value = r.nextInt(max - min + 1) + min;
        }
    }
    
    


    Now, you can have a Monster class as well:

    public class Monster
    {
        private Stat health;
    
        public Monster(int minHealth, int maxHealth)
        {
            health = new Stat(minHealth, maxHealth);
            health.getRandomValue();
        }
    }
    
    


    So, in main game code you create a monster:

    Monster rat = new Monster(3, 5);
    
    


    But this would also work with a weapon:

    class Weapon
    {
        Stat power;
        Stat defense;
        public Weapon(String kind) // This should really be enum, but that's another conversation.
        {
            if(kind.equals("sword"))
            {
                power = new Stat(5, 4);
                defense = new Stat(1,2);
            }
        }
    
        public int getDamage()
        {
            power.setRandomValue();
            return power.getValue();
        }
    }
    
    


    And you will notice that as you try to use the classes you create, there will be moments of "it would be nice if it had ... so I could more easily do ...", and then you change the code to reflect that.

    The elephant in the room is your labeled jumps, but definitely explore the space, and see how it all works.
  2. In Topic: How can I improve this code? Text Based Game

    Posted 30 Apr 2016

    Quote

    I've implemented this already, and it's working great!


    Let's see the new code then. Otherwise, I'm just going to be grasping at straws in how to advise further.
  3. In Topic: How can I improve this code? Text Based Game

    Posted 30 Apr 2016

    What I would do for starters just to get my feet wet in using classes would be to create a simple GameState object, which holds everything in your code. Then main creates an instance, and uses that.

    Obviously I don't want to ruin the fun of you doing this for your own code, so I created a quick text game too. It's riddled with repeated code, constants that should be variables, and entirely in main -- on purpose. It's just a teaching tool.

    import java.util.*;
    public class Game
    {
        public static void main(String[] args)
        {
            Random rng = new Random();
            Scanner kb = new Scanner(System.in);
            int choice = 0;
            int monster = rng.nextInt(5 - 3 + 1) + 3; // min=3 max=5;
            int player = 10;
            int gold = 0;
            System.out.println("A monster approaches.");
            System.out.println("===========================================");
            while(choice != 3)
            {
                System.out.println("Player : " + player);
                System.out.println("Monster: " + monster);
                System.out.println("Gold   : " + gold);
            
                System.out.println("Action:");
                System.out.println("1. Attack");
                System.out.println("2. Run");
                System.out.println("3. Quit");
                
                System.out.println("Choice: ");
                choice = kb.nextInt();          // BUG: if you enter non-number it doesn't work.
                
                if(choice == 1)
                {
                    System.out.println("You attack for 1 damage.");
                    monster--;
                    if(monster <= 0)
                    {
                        System.out.println("You kill the monster.");
                        System.out.println("A monster approaches.");
                        monster = rng.nextInt(5 - 3 + 1) + 3; // min=3 max=5;
                        gold += rng.nextInt(5 - 3 + 1) + 3; // min=3 max=5;
                    }
                    else
                    {
                        System.out.println("Monster attacks for 1 damage.");
                        player--;
                        if(player <= 0)
                        {
                            System.out.println("You have died.");
                            System.out.println("Play again?");
                            System.out.println("1. Yes");
                            System.out.println("2. No");
                            choice = kb.nextInt();
                            if(choice == 1)
                            {
                                player = 10;
                                monster = rng.nextInt(5 - 3 + 1) + 3; // min=3 max=5;
                            }
                            else
                            {
                                choice = 3;
                                System.out.println("See you next battle.");
                                continue;   
                            }
                        }
                    
                    }
                }
                else if(choice == 2)
                {
                    int droppedGold = rng.nextInt(5 - 3 + 1) + 3; // min=3 max=5;
                    if(droppedGold > gold)
                        droppedGold = gold;
                        
                    gold -= droppedGold;
                    if(droppedGold > 0)
                        System.out.println("You run away and drop " + droppedGold + " gold.");
                    else
                        System.out.println("You run away.");
                        
                    monster = rng.nextInt(5 - 3 + 1) + 3; // min=3 max=5;
                    continue;
                }
                else if(choice == 3)
                {
                    System.out.println("See you next battle.");
                    break;
                }
                else
                    System.out.println("That is not a valid choice.");
            }
        }
    }
    
    


    So, let's improve this a little.

    First, we will do what I suggested, which is create a class called GameState.

    public class GameState
    {
        public int monster = 0;
        public int player = 10;
        public int gold = 0;
        
        public GameState()
        {
        
        }
    }
    
    


    Then, we use it in the main class. Notice that we create an instance of it, and anywhere we access the variables, it's on the object instance like
    state.player
    
    .

    import java.util.*;
    public class Game
    {
        public static void main(String[] args)
        {
            Random rng = new Random();
            Scanner kb = new Scanner(System.in);
            GameState state = new GameState();
            state.monster = rng.nextInt(5 - 3 + 1) + 3; // min=3 max=5;
            
            int choice = 0;
            System.out.println("A monster approaches.");
            System.out.println("===========================================");
            while(choice != 3)
            {
                System.out.println("Player : " + state.player);
                System.out.println("Monster: " + state.monster);
                System.out.println("Gold   : " + state.gold);
            
                System.out.println("Action:");
                System.out.println("1. Attack");
                System.out.println("2. Run");
                System.out.println("3. Quit");
                
                System.out.println("Choice: ");
                choice = kb.nextInt();          // BUG: if you enter non-number it doesn't work.
                
                if(choice == 1)
                {
                    System.out.println("You attack for 1 damage.");
                    state.monster--;
                    if(state.monster <= 0)
                    {
                        System.out.println("You kill the monster.");
                        System.out.println("A monster approaches.");
                        state.monster = rng.nextInt(5 - 3 + 1) + 3; // min=3 max=5;
                        state.gold += rng.nextInt(5 - 3 + 1) + 3; // min=3 max=5;
                    }
                    else
                    {
                        System.out.println("Monster attacks for 1 damage.");
                        state.player--;
                        if(state.player <= 0)
                        {
                            System.out.println("You have died.");
                            System.out.println("Play again?");
                            System.out.println("1. Yes");
                            System.out.println("2. No");
                            choice = kb.nextInt();
                            if(choice == 1)
                            {
                                state.player = 10;
                                state.monster = rng.nextInt(5 - 3 + 1) + 3; // min=3 max=5;
                            }
                            else
                            {
                                choice = 3;
                                System.out.println("See you next battle.");
                                continue;   
                            }
                        }
                    
                    }
                }
                else if(choice == 2)
                {
                    int droppedGold = rng.nextInt(5 - 3 + 1) + 3; // min=3 max=5;
                    if(droppedGold > state.gold)
                        droppedGold = state.gold;
                        
                    state.gold -= droppedGold;
                    if(droppedGold > 0)
                        System.out.println("You run away and drop " + droppedGold + " gold.");
                    else
                        System.out.println("You run away.");
                        
                    state.monster = rng.nextInt(5 - 3 + 1) + 3; // min=3 max=5;
                    continue;
                }
                else if(choice == 3)
                {
                    System.out.println("See you next battle.");
                    break;
                }
                else
                    System.out.println("That is not a valid choice.");
            }
        }
    }
    
    


    Now, the problem with this way of doing things is that we have not actually encapsulated any data. Code everywhere (as long as it has an instance of the object) can modify the state of the GameState object. So, instead we want to create getter and setter methods which will retrieve the information or modify it.

    The GameState object now looks like this:

    public class GameState
    {
        private int monster = 0;
        private int player = 10;
        private int gold = 0;
        
        public GameState()
        {
        
        }
        
        public boolean isMonsterAlive()
        {
            return monster > 0;
        }
        
        public int getMonster()
        {
            return monster;
        }
        
        public void setMonster(int health)
        {
            monster = health;
        }
        
        public void damageMonster(int damage)
        {
            monster -= damage;
        }
        
        public boolean isPlayerAlive()
        {
            return player > 0;
        }
        
        public int getPlayer()
        {
            return player;
        }
        
        public void setPlayer(int health)
        {
            player = health;
        }
        
        public void damagePlayer(int damage)
        {
            player -= damage;
        }
        
        public int getGold()
        {
            return gold;
        }
        
        public boolean hasGold(int amount)
        {
            return gold >= amount;
        }
        
        public void addGold(int amount)
        {
            gold += amount;
        }
        
        public void removeGold(int amount)
        {
            gold -= amount;
        }
    }
    
    


    And so, we have to update the main code to use the methods of the object instead of directly accessing member variables:

    import java.util.*;
    public class Game
    {
        public static void main(String[] args)
        {
            Random rng = new Random();
            Scanner kb = new Scanner(System.in);
            GameState state = new GameState();
            state.setMonster( rng.nextInt(5 - 3 + 1) + 3 ); // min=3 max=5;
            
            int choice = 0;
            System.out.println("A monster approaches.");
            System.out.println("===========================================");
            while(choice != 3)
            {
                System.out.println("Player : " + state.getPlayer());
                System.out.println("Monster: " + state.getMonster());
                System.out.println("Gold   : " + state.getGold());
            
                System.out.println("Action:");
                System.out.println("1. Attack");
                System.out.println("2. Run");
                System.out.println("3. Quit");
                
                System.out.println("Choice: ");
                choice = kb.nextInt();          // BUG: if you enter non-number it doesn't work.
                
                if(choice == 1)
                {
                    System.out.println("You attack for 1 damage.");
                    state.damageMonster(1);
                    if( !state.isMonsterAlive() )
                    {
                        System.out.println("You kill the monster.");
                        System.out.println("A monster approaches.");
                        state.setMonster( rng.nextInt(5 - 3 + 1) + 3 ); // min=3 max=5;
                        state.addGold( rng.nextInt(5 - 3 + 1) + 3 ); // min=3 max=5;
                    }
                    else
                    {
                        System.out.println("Monster attacks for 1 damage.");
                        state.damagePlayer(1);
                        if( !state.isPlayerAlive() )
                        {
                            System.out.println("You have died.");
                            System.out.println("Play again?");
                            System.out.println("1. Yes");
                            System.out.println("2. No");
                            choice = kb.nextInt();
                            if(choice == 1)
                            {
                                state.setPlayer(10);
                                state.setMonster( rng.nextInt(5 - 3 + 1) + 3 ); // min=3 max=5;
                            }
                            else
                            {
                                choice = 3;
                                System.out.println("See you next battle.");
                                continue;   
                            }
                        }
                    
                    }
                }
                else if(choice == 2)
                {
                    int droppedGold = rng.nextInt(5 - 3 + 1) + 3; // min=3 max=5;
                    if( !state.hasGold(droppedGold) )
                        droppedGold = state.getGold();
                        
                    state.removeGold( droppedGold );
                    if(droppedGold > 0)
                        System.out.println("You run away and drop " + droppedGold + " gold.");
                    else
                        System.out.println("You run away.");
                        
                    state.setMonster( rng.nextInt(5 - 3 + 1) + 3 ); // min=3 max=5;
                    continue;
                }
                else if(choice == 3)
                {
                    System.out.println("See you next battle.");
                    break;
                }
                else
                    System.out.println("That is not a valid choice.");
            }
        }
    }
    
    


    We can keep going and going with this thing, but I want to leave it at that for now. You can try this idea with your code and see how it goes.

    Have fun.
  4. In Topic: How can I improve this code? Text Based Game

    Posted 29 Apr 2016

    Congratulations on completing a playable game. Here is a bug:

    >You strike the Zombie for 7 damage.
    >And recievce 13 in retaliation.
    
    	Your HP: -1
    	Zombie's HP: 82
    
    	What would you like to do?
    	1. Attack
    	2. Drink health potion
    	3. Drink strength potion
    
    1
    
    >You strike the Zombie for 226 damage.
    >And recievce 17 in retaliation.
    
    You fall haven taken too much damage!
    
    


    My HP was -1, but I was still alive. So, that should be fixed.

    So, let's talk about the code.

                // ENEMY GENERATE       
                System.out.println("--------------------------------------------------");
                int enemyHealth = rand.nextInt(maxEnemyHealth);
                if(enemyHealth < 40) {
                     enemyHealth = minEnemyHealth; 
    
    


    We talked about this in another thread. cfoley gave you the solution to use that will not be biased toward low numbers. Your way works, but understand that a great deal of the enemies will simply have 40 health.

    Here's the suggested plan:

    Fix the life bug I mentioned. Then, save the work you've done in a separate file. Continue working on this as you are, and try to add all the features that you want. Try to understand what is becoming painful about working with your code as you try to add new features. Just let it become a tangled mess if it must, but fight hard against it all the same. When the code gets to the point where you simply cannot seem to make progress on adding something new that you want, go back to the original. Try to identify the areas that would have been better off encapsulated from the start to prevent future meltdown. Make a copy of the file, and try again. Repeat as long as you like.

    The bottom line is that you have a program that works for a concept that is very object friendly, but you have a great opportunity to gain a lot of valuable experience by understanding first-hand what OOP tries to solve. You won't get that if you simply jump right to object oriented principles.

    People might argue that you are wasting time, and you will be if you give up on this project early. However, if you stick with it, you will learn from your mistakes, and have reasoning backed by empirical evidence.

    You're just starting out right? Don't seek a bunch of advice about how to "improve this code." Work with the code, understand it, manipulate it as it exists, and truly grasp how to improve this code. You'll understand better what I mean if you try it.

    Take care. Oh, and nice game:

    You hit the floor and the darkness first
    surrounds, then consumes you...
    
    	Total enemies killed: 33
    	Total EXP gained: 1551
    	Level: 5
    
    
  5. In Topic: What should I do next? feels like going nowhere...

    Posted 28 Apr 2016

    Quote

    A simple project would be - snake? (dont have any other idea).

    If so where should I start reading about it? by looking online I found guides that just shows you the code, I dont like learning this way /:


    Actually, figuring out how to do snake yourself is pretty difficult. If you follow a tutorial and see how people do it, it's a breeze. Doing it all yourself? You won't be ready.

    A much simpler game would be like space invader, but instead of the enemies cycling back and forth, they just randomly spawn outside of the screen and "fall" towards the player, who scrolls horizontally at the bottom of the screen and shoots the enemies.

    Snake is a gridbased game. There is a lot to think about. Like I said, easy to follow a tutorial and get it done, if that's your thing. But, if you really want to write something yourself, you can write this space shooter game.

    • Put a player on the screen
    • Move player left/right when pressing respective direction
    • Prevent player from exiting the screen
    • Show bullet shooting when pressing key
    • Remove bullet when out of screen
    • Random spawn an enemy outside of screen and change y position by a speed every tick
    • Remove enemy when out of bottom of screen
    • Write collision code such that the bullet hitting enemy removes enemy
    • Add a score counter display
    • Increment score when bullet collides
    • Add a lives counter
    • Decrement lives when enemy collides with player and restart level.
    • Eventually add powerups and such...


    So, that's still a ton of stuff to learn. How to load resources (images,music,sfx)? How to do collision? How to draw to screen? How to make a game loop? How to make a game loop that restarts on death? It's all doable by thinking it out without tutorials, which is where you are going to learn the most.

    I like your attitude though. Tutorials can make you a monkey-see-monkey-do programmer without much grasp on what is really going on.

My Information

Member Title:
.
Age:
Age Unknown
Birthday:
Birthday Unknown
Gender:

Contact Information

E-mail:
Private

Comments

MentalFloss has no profile comments yet. Why not say hello?