Page 1 of 2 12 LastLast
Results 1 to 20 of 22

Thread: It's Alive!

  1. #1
    Snoman is offline Member
    Join Date
    Jul 2010
    Posts
    9
    Rep Power
    0

    Default It's Alive!

    I just finished my first working program (not including "Hello World!"). It's not very elegant or incredibly fun, but it is something. I was wondering if someone on the forums would be kind enough to look at the code and perhaps suggest a more elegant solution to some of the coding. It's all text based, no GUI yet.


    Java Code:
    import java.io.*;
    public class Main {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // TODO code application logic here.
    
            City P1 = new City();
            City P2 = new City();
            String userInput = "";
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    
            System.out.println("Game Start");
            while (P1.Wealth > 0 & P2.Wealth > 0)
            {
                {
                 P1.startTurn();
                 while (P1.myTurn)
                 {
                    System.out.println("Player1: What would you like to do?");
                     try {
                        userInput = br.readLine();
                        }
                    catch (IOException ioe) {
                        System.out.println("Does not compute!");
                        }
                    if (userInput.equalsIgnoreCase("print"))
                        { System.out.println("What would you like to print?");
                        try {
                            userInput = br.readLine();
                            }
                        catch (IOException ioe) {
                            System.out.println("Does not compute!");
                            }
                      if (userInput.equalsIgnoreCase("army"))
                        { P1.printArmy();
                        } else if (userInput.equalsIgnoreCase("all"))
                        { P1.printAll();
                        } else if (userInput.equalsIgnoreCase("build"))
                        { P1.printBuildings();
                        } else if (userInput.equalsIgnoreCase("resources"))
                        { P1.printResources();
                        } else if (userInput.equalsIgnoreCase("stats"))
                        { P1.printStats();
                        } else System.out.println("Huh?");
                      }
                    else if (userInput.equalsIgnoreCase("end"))
                    { P1.endTurn();
                    } else if (userInput.equalsIgnoreCase("build"))
                    { System.out.println("What would you like to build?");
                      try {
                            userInput = br.readLine();
                            }
                        catch (IOException ioe) {
                            System.out.println("Does not compute!");
                            }
                      if (userInput.equalsIgnoreCase("wm"))
                      { P1.buildWoodmill();
                      } else if (userInput.equalsIgnoreCase("sq"))
                      { P1.buildStonequarry();
                      } else if (userInput.equalsIgnoreCase("b"))
                      { P1.buildBakery();
                      } else if (userInput.equalsIgnoreCase("h"))
                      { P1.buildHouse();
                      } else if (userInput.equalsIgnoreCase("t"))
                      { P1.buildTower();
                      } else if (userInput.equalsIgnoreCase("$"))
                      { P1.buildBank();
                      } else System.out.println("Huh?");
                      }
                    else if (userInput.equalsIgnoreCase("train"))
                    { System.out.println("What would you like to train?");
                      try {
                            userInput = br.readLine();
                            }
                        catch (IOException ioe) {
                            System.out.println("Does not compute!");
                            }
                      if (userInput.equalsIgnoreCase("c"))
                      { P1.buildCavalry(1);
                      } else if (userInput.equalsIgnoreCase("a"))
                      { P1.buildArcher(1);
                      } else if (userInput.equalsIgnoreCase("s"))
                      { P1.buildSoldier(1);
                      }
                    }
                  else if (userInput.equalsIgnoreCase("attack"))
                  { P1.Attack(P2);
    
                 }
                 }
                 P2.startTurn();
                 while (P2.myTurn)
                 {
                    System.out.println("Player1: What would you like to do?");
                     try {
                        userInput = br.readLine();
                        }
                    catch (IOException ioe) {
                        System.out.println("Does not compute!");
                        }
                    if (userInput.equalsIgnoreCase("print"))
                        { System.out.println("What would you like to print?");
                        try {
                            userInput = br.readLine();
                            }
                        catch (IOException ioe) {
                            System.out.println("Does not compute!");
                            }
                      if (userInput.equalsIgnoreCase("army"))
                        { P1.printArmy();
                        } else if (userInput.equalsIgnoreCase("all"))
                        { P1.printAll();
                        } else if (userInput.equalsIgnoreCase("build"))
                        { P1.printBuildings();
                        } else if (userInput.equalsIgnoreCase("resources"))
                        { P1.printResources();
                        } else if (userInput.equalsIgnoreCase("stats"))
                        { P1.printStats();
                        } else System.out.println("Huh?");
                      }
                    else if (userInput.equalsIgnoreCase("end"))
                    { P1.endTurn();
                    } else if (userInput.equalsIgnoreCase("build"))
                    { System.out.println("What would you like to build?");
                      try {
                            userInput = br.readLine();
                            }
                        catch (IOException ioe) {
                            System.out.println("Does not compute!");
                            }
                      if (userInput.equalsIgnoreCase("wm"))
                      { P1.buildWoodmill();
                      } else if (userInput.equalsIgnoreCase("sq"))
                      { P1.buildStonequarry();
                      } else if (userInput.equalsIgnoreCase("b"))
                      { P1.buildBakery();
                      } else if (userInput.equalsIgnoreCase("h"))
                      { P1.buildHouse();
                      } else if (userInput.equalsIgnoreCase("t"))
                      { P1.buildTower();
                      } else if (userInput.equalsIgnoreCase("$"))
                      { P1.buildBank();
                      } else System.out.println("Huh?");
                      }
                    else if (userInput.equalsIgnoreCase("train"))
                    { System.out.println("What would you like to train?");
                      try {
                            userInput = br.readLine();
                            }
                        catch (IOException ioe) {
                            System.out.println("Does not compute!");
                            }
                      if (userInput.equalsIgnoreCase("c"))
                      { P1.buildCavalry(1);
                      } else if (userInput.equalsIgnoreCase("a"))
                      { P1.buildArcher(1);
                      } else if (userInput.equalsIgnoreCase("s"))
                      { P1.buildSoldier(1);
                      }
                    }
                  else if (userInput.equalsIgnoreCase("attack"))
                  { P1.Attack(P2);
                  } else System.out.println("Huh?");
                }
                }
            }
        }
    }
    Java Code:
    public class City {
        // Buildings in a city
        int Woodmill = 2;
        int Stonequarry = 2;
        int Bakery = 0;
        int House = 1;
        int Tower = 0;
        int Bank = 0;
        // Resources in a city
        int Wood = 300;
        int Stone = 150;
        int Food = 50;
        int Population = 10;
        // Army of a city
        int Cavalry = 0;
        int Archer = 0;
        int Soldier = 0;
        // Stats of a city
        int Power;
        int Defense;
        int Wealth = 1000;
        // Turn
        boolean myTurn = false;
    
        //Methods of a city
    
        // To start the turn
        void startTurn (){
            System.out.println("Start of your turn.");
            this.Wood = this.Wood + (this.Woodmill*5);
            this.Stone = this.Stone + (this.Stonequarry*3);
            this.Wealth = this.Wealth + (this.Bank*5);
            this.Food = this.Food + (this.Bakery*3);
            this.calcPower();
            this.calcDefense();
            this.myTurn = true;
        }
        // To build a wood mill
        void buildWoodmill (){
            if (this.Wood >= 50)
            {
                if (this.Stone >= 25)
                {
                    if (this.Population >= 3)
                    { this.Woodmill = this.Woodmill + 1;
                      this.Wood = this.Wood - 50;
                      this.Stone = this.Stone - 25;
                      this.Population = this.Population - 3;
                      System.out.println("Congratulations, you built a wood mill.");
                    } else
                    {
                        System.out.println("You don't have enough population.");
                    }
                } else
                {
                    System.out.println("You don't have enough stone.");
                }
            } else
            {
                System.out.println("You don't have enough wood.");
            }
        }
        // To build a stone quarry
        void buildStonequarry (){
            if (this.Wood >= 25)
            {
                if (this.Stone >= 50)
                {
                    if (this.Population >= 3)
                    { this.Stonequarry = this.Stonequarry + 1;
                      this.Wood = this.Wood - 25;
                      this.Stone = this.Stone - 50;
                      this.Population = this.Population - 3;
                      System.out.println("Congratulations, you built a stone quarry.");
                    } else
                    {
                        System.out.println("You don't have enough population.");
                    }
                } else
                {
                    System.out.println("You don't have enough stone.");
                }
            } else
            {
                System.out.println("You don't have enough wood.");
            }
        }
        // To build a bakery
        void buildBakery (){
            if (this.Wood >= 30)
            {
                if (this.Stone >= 30)
                {
                    if (this.Population >= 2)
                    { this.Bakery = this.Bakery + 1;
                      this.Wood = this.Wood - 30;
                      this.Stone = this.Stone - 30;
                      this.Population = this.Population - 2;
                      System.out.println("Congratulations, you built a bakery.");
                    } else
                    {
                        System.out.println("You don't have enough population.");
                    }
                } else
                {
                    System.out.println("You don't have enough stone.");
                }
            } else
            {
                System.out.println("You don't have enough wood.");
            }
        }
        // To build a house
        void buildHouse (){
            if (this.Wood >= 50)
            {
                if (this.Stone >= 50)
                { this.House = this.House + 1;
                  this.Population = this.Population + 10;
                  this.Wood = this.Wood - 50;
                  this.Stone = this.Stone - 50;
                  System.out.println("Congratulations, you built a house.");
                } else
                {
                    System.out.println("You don't have enough stone.");
                }
            } else
            {
                System.out.println("You don't have enough wood.");
            }
        }
        // To build a tower
        void buildTower (){
            if (this.Wood >= 30)
            {
                if (this.Stone >= 70)
                {
                    if (this.Population >= 3)
                    { this.Tower = this.Tower + 1;
                      this.Wood = this.Wood - 30;
                      this.Stone = this.Stone - 70;
                      this.Population = this.Population - 3;
                      System.out.println("Congratulations, you built a tower.");
                    } else
                    {
                        System.out.println("You don't have enough population.");
                    }
                } else
                {
                    System.out.println("You don't have enough stone.");
                }
            } else
            {
                System.out.println("You don't have enough wood.");
            }
        }
        // To build a bank
        void buildBank (){
            if (this.Wood >= 100)
            {
                if (this.Stone >= 150)
                {
                    if (this.Population >= 5)
                    { this.Bank = this.Bank + 1;
                      this.Wood = this.Wood - 100;
                      this.Stone = this.Stone - 150;
                      this.Population = this.Population - 5;
                      System.out.println("Congratulations, you built a bank.");
                    } else
                    {
                        System.out.println("You don't have enough population.");
                    }
                } else
                {
                    System.out.println("You don't have enough stone.");
                }
            } else
            {
                System.out.println("You don't have enough wood.");
            }
        }
        // To build a soldier
        void buildSoldier (int x){
            if (this.Wood >= 10*x)
            {
                if (this.Stone >= 15*x)
                {
                    if (this.Food >= 10*x)
                    {
                        if (this.Population >= 1*x)
                        { this.Soldier = this.Soldier + 1*x;
                          this.Wood = this.Wood - 10*x;
                          this.Stone = this.Stone - 15*x;
                          this.Food = this.Food - 10*x;
                          this.Population = this.Population - 1*x;
                          System.out.println("Congratulations, you built " + x + " soldier(s).");
                        } else
                        {
                            System.out.println("You don't have enough population.");
                        }
                    } else
                    {
                        System.out.println("You don't have enough food.");
                    }
                } else
                {
                    System.out.println("You don't have enough stone.");
                }
            } else
            {
                System.out.println("You don't have enough wood.");
            }
        }
        // To build an archer
        void buildArcher (int x){
            if (Wood >= 7*x)
            {
                if (Stone >= 10*x)
                {
                    if (Food >= 7*x)
                    {
                        if (Population >= 1*x)
                        { Archer = Archer + 1*x;
                          Wood = Wood - 7*x;
                          Stone = Stone - 10*x;
                          Food = Food - 7*x;
                          Population = Population - 1*x;
                          System.out.println("Congratulations, you built " + x + " archer(s).");
                        } else
                        {
                            System.out.println("You don't have enough population.");
                        }
                    } else
                    {
                        System.out.println("You don't have enough food.");
                    }
                } else
                {
                    System.out.println("You don't have enough stone.");
                }
            } else
            {
                System.out.println("You don't have enough wood.");
            }
        }
        // To build a cavalry
        void buildCavalry (int x){
            if (Wood >= 25*x)
            {
                if (Stone >= 30*x)
                {
                    if (Food >= 25*x)
                    {
                        if (Population >= 3*x)
                        { Cavalry = Cavalry + 1*x;
                          Wood = Wood - 25*x;
                          Stone = Stone - 30*x;
                          Food = Food - 25*x;
                          Population = Population - 3*x;
                          System.out.println("Congratulations, you built " + x + " cavalry.");
                        } else
                        {
                            System.out.println("You don't have enough population.");
                        }
                    } else
                    {
                        System.out.println("You don't have enough food.");
                    }
                } else
                {
                    System.out.println("You don't have enough stone.");
                }
            } else
            {
                System.out.println("You don't have enough wood.");
            }
        }
        // To calculate defense
        void calcDefense (){
            Defense = Tower*10 + Archer*3 + Cavalry*2 + Soldier*1;
        }
        // To calculate power
        void calcPower (){
            Power = Cavalry*7 + Soldier*5 + Archer*2;
        }
        // To attack the other player
        void Attack (City city){
            if ((this.Power - city.Defense) > 0)
            {
                if (city.Wealth > this.Power - city.Defense)
                { city.Wealth = city.Wealth - (this.Power - city.Defense);
                  System.out.println("Your stats");
                  this.printStats();
                  System.out.println("Enemy stats");
                  city.printStats();
                  this.Archer = this.Archer / 2;
                  this.Cavalry = this.Cavalry / 2;
                  this.Soldier = this.Soldier / 2;
                } else
                {
                    city.Wealth = 0;
                    this.printAll();
                    city.printAll();
                    System.out.println("You win!");
                }
            } else
            {
                System.out.println("You do not have enough power to deal and damage.");
            }
        }
        // To end the turn
        void endTurn (){
            this.calcDefense();
            this.calcPower();
            System.out.println("End of your turn.");
            this.myTurn = false;
        }
        // To print everything
        void printAll (){
            this.printResources();
            this.printArmy();
            this.printStats();
            this.printBuildings();
        }
        // To print only resources
        void printResources (){
            System.out.println("Resources");
            System.out.println("Wood: " + Wood);
            System.out.println("Stone: " + Stone);
            System.out.println("Food: " + Food);
            System.out.println("Idle Population: " + Population);
        }
        // To print only Army
        void printArmy (){
            System.out.println("Army");
            System.out.println("Cavalry: " + Cavalry);
            System.out.println("Archer: " + Archer);
            System.out.println("Soldier: " + Soldier);
        }
        // To print only Stats
        void printStats (){
            System.out.println("Stats");
            System.out.println("Power: " + Power);
            System.out.println("Defense: " + Defense);
            System.out.println("Wealth: " + Wealth);
        }
        // To print only Buildings
        void printBuildings (){
            System.out.println("Buildings");
            System.out.println("Wood Mills: " + Woodmill);
            System.out.println("Stone Quarries: " + Stonequarry);
            System.out.println("Bakeries: " + Bakery);
            System.out.println("Houses: " + House);
            System.out.println("Towers: " + Tower);
            System.out.println("Banks: " + Bank);
        }
    }
    Questions:
    Is there a better way to read lines of input than what I was using?
    Have I done anything horribly wrong?
    What are the biggest things I need to improve on?

    Thanks,
    Snoman
    Last edited by Snoman; 07-20-2010 at 11:47 PM. Reason: code

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Why not just post your code (with code tags) here? Also let us know if you have specific questions answered about the code.

  3. #3
    Snoman is offline Member
    Join Date
    Jul 2010
    Posts
    9
    Rep Power
    0

    Default

    The code is a bit long, which is why I refrained from posting it.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    What you need to do is refactor your code into more manageable logical divisions, into more classes (such as Player as one obvious example), and each class into several methods. You need to shrink your main method drastically and try to use methods and classes to reduce the enormous amount of redundancy present. You will want to assume your user is an idiot, knows nothing about your program and will be easily frustrated. I would prompt the user with suggested responses rather than just give open ended questions without any clue as to what are the few accepted replies.

    Much luck.

  5. #5
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    19

    Default

    Quote Originally Posted by Fubarable View Post
    What you need to do is refactor your code into more manageable logical divisions, into more classes
    OO concepts, then OP can build up small logic (see how many conditions...) on the application.

  6. #6
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    Hmmm where to begin oh yes well done on your first program that works.

    Now there is no prizes for 1million lines of code when 10 are needed. Object Orientated Principles OOP read every book you can on the subject AND APPLY THE PRINCIPLES in your code. Fubarable has mentioned a few examples. We all start out with a mammoth of a class, main method, etc, just desperate to get it to work so do not worry. You are asking the right questions.

    You are doing well and seem enthusiastic just read the right material and with the same dedication you put into this program I have no doubt you will be fine.

  7. #7
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    4

    Default

    One thing I just thought I'd mention... you may or may not have noticed this as well, Snoman, but it's worth showing you.

    Java Code:
        void buildWoodmill (){
            if (this.Wood >= 50)
            {
                if (this.Stone >= 25)
                {
                    if (this.Population >= 3)
                    { this.Woodmill = this.Woodmill + 1;
                      this.Wood = this.Wood - 50;
                      this.Stone = this.Stone - 25;
                      this.Population = this.Population - 3;
                      System.out.println("Congratulations, you built a wood mill.");
                    } else
                    {
                        System.out.println("You don't have enough population.");
                    }
                } else
                {
                    System.out.println("You don't have enough stone.");
                }
            } else
            {
                System.out.println("You don't have enough wood.");
            }
        }
    You'll find that in all your build*() functions, this is pretty standard. You could do something like this instead:

    Java Code:
    boolean prepareBuild(int RequiredWood, int RequiredStone, int RequiredPopulation) {
    	if (this.Wood < RequiredWood) {
    		System.out.println("You don't have enough wood.");
    		return false;
    	}
    	if (this.Stone < RequiredStone) {
    		System.out.println("You don't have enough stone.");
    		return false;
    	}
    	if (this.Population < RequiredPopulation) {
    		System.out.println("You don't have enough population.");
    		return false;
    	}
    	this.Wood -= RequiredWood;
    	this.Stone -= RequiredStone;
    	this.Population -= RequiredPopulation;
    	return true;
    }
    Now your other functions look like this:
    Java Code:
    void buildWoodmill() {
    	boolean Success = prepareBuild(50,25,3));
    	if (Success == true) {
    		this.Woodmill++;
    		System.out.println("Congratulations, you built a wood mill.");
    	}
    }
    void buildHouse() {
    	boolean Success = prepareBuild(50,50,0));
    	if (Success == true) {
    		this.House++;
    		System.out.println("Congratulations, you built a house.");
    	}
    }
    void buildTower() {
    	boolean Success = prepareBuild(30,70,3));
    	if (Success == true) {
    		this.Tower++;
    		System.out.println("Congratulations, you built a tower.");
    	}
    }

    Just a suggestion; if you don't like it don't use it--but it's much preferred if working with groups of people and code modifications (i.e. in the future, if you need to add something other than Wood and Stone, for example).
    Last edited by Zack; 07-22-2010 at 01:17 AM. Reason: Fixed up some codes to make them a little neater.

  8. #8
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    19

    Default

    Quote Originally Posted by al_Marshy_1981 View Post
    You are doing well and seem enthusiastic just read the right material and with the same dedication you put into this program I have no doubt you will be fine.
    Get the right things for your safe in future. :)

  9. #9
    Snoman is offline Member
    Join Date
    Jul 2010
    Posts
    9
    Rep Power
    0

    Default

    Ok, I've attempted to refactor my code. It feels a lot cleaner to me, but I'd like to see what you guys think, and if you have any more suggestions for things I should do.

    I am having one slight problem now, when I input army then one of the units it works fine, but when I input how many of the unit I'd like it to create it creates a lot more. After this is goes back to the starting prompt, outputs "Huh?", and opens the starting prompt again. If someone happens across something that might cause this while they are looking at the code I'd appreciate it if you would tell me.

    This is what it looks like:
    Player1, would you like to build, print, train, attack, or end?
    train
    Would you like to build archers(a), cavalry(c), or soldiers(s)?
    a
    How many archers would you like to make?
    3
    Congratulations, you built 51 archer(s).
    Player1, would you like to build, print, train, attack, or end?
    Huh?
    Player1, would you like to build, print, train, attack, or end?

    Main
    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package citygame12;
    import java.io.*;
    public class Main {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // TODO code application logic here.
    
            City P1 = new City();
            City P2 = new City();
            Reader reader = new Reader();
            String userInput = "";
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    
            System.out.println("Game Start");
            while (P1.Wealth > 0 & P2.Wealth > 0)
            {
                {
                 P1.startTurn();
                 while (P1.myTurn)
                 {
                    System.out.println("Player1, would you like to build, print, train, attack, or end?");
                    reader.checkInput(P1, P2);
                 }
                 P2.startTurn();
                 while (P2.myTurn)
                 {
                    System.out.println("Player2, would you like to build, print, train, attack, or end?");
                    reader.checkInput(P2, P1);
                 }
                }
            }
        }
    }
    City
    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package citygame12;
    
    /**
     *
     * @author Flying Bear
     */
    public class City {
        // Buildings in a city
        int Woodmill = 2;
        int Stonequarry = 2;
        int Bakery = 0;
        int House = 1;
        int Tower = 0;
        int Bank = 0;
        // Resources in a city
        int Wood = 300;
        int Stone = 150;
        int Food = 50;
        int Population = 10;
        // Army of a city
        int Cavalry = 0;
        int Archer = 0;
        int Soldier = 0;
        // Stats of a city
        int Power;
        int Defense;
        int Wealth = 1000;
        // Turn
        boolean myTurn = false;
    
        Printer printer = new Printer();
    
        //Methods of a city
    
        // To start the turn
        void startTurn (){
            System.out.println("Start of your turn.");
            this.Wood = this.Wood + (this.Woodmill*20);
            this.Stone = this.Stone + (this.Stonequarry*20);
            this.Wealth = this.Wealth + (this.Bank*10);
            this.Food = this.Food + (this.Bakery*15);
            this.calcPower();
            this.calcDefense();
            this.myTurn = true;
        }
        // To prepare a build
        boolean prepareBuild (int reqWood, int reqStone, int reqPop, int reqFood) {
            if (this.Wood < reqWood) {
                System.out.println("You don't have enough wood.");
                return false;
            }
            if (this.Stone < reqStone) {
                System.out.println("You don't have enough stone.");
                return false;
            }
            if (this.Population < reqPop) {
                System.out.println("You don't have enough population.");
                return false;
            }
            if (this.Food < reqFood) {
                System.out.println("You don't have enough food.");
                return false;
            }
            this.Wood -= reqWood;
            this.Stone -= reqStone;
            this.Population -= reqPop;
            return true;
        }
        // To build a wood mill
        void buildWoodmill (){
            boolean Success = prepareBuild (50, 25, 3, 0);
            if (Success == true) {
                this.Woodmill++;
                System.out.println("Congratulations, you built a wood mill");
            }
        }
        // To build a stone quarry
        void buildStonequarry (){
            boolean Success = prepareBuild (25, 50, 3, 0);
            if (Success == true) {
                this.Stonequarry++;
                System.out.println("Congratulations, you built a stone quarry.");
            }
        }
        // To build a bakery
        void buildBakery (){
            boolean Success = prepareBuild (30, 30, 2, 0);
            if (Success == true) {
                this.Bakery++;
                System.out.println("Congratulations, you built a bakery.");
            }
        }
        // To build a house
        void buildHouse (){
            boolean Success = prepareBuild (50, 50, 0, 0);
            if (Success == true) {
                this.House++;
                this.Population += 10;
                System.out.println("Congratulations, you built a house.");
            }
        }
        // To build a tower
        void buildTower (){
            boolean Success = prepareBuild (30, 70, 3, 0);
            if (Success == true) {
                this.Tower++;
                System.out.println("Congratulations, you built a tower.");
            }
        }
        // To build a bank
        void buildBank (){
            boolean Success = prepareBuild (100, 150, 5, 0);
            if (Success == true) {
                this.Bank++;
                System.out.println("Congratulations, you built a bank.");
            }
        }
        // To build a soldier
        void buildSoldier (int x){
            boolean Success = prepareBuild (10*x, 15*x, 1*x, 10*x);
            if (Success == true) {
                this.Soldier += x;
                System.out.println("Congratulations, you built " + x + " soldier(s).");
            }
        }
        // To build an archer
        void buildArcher (int x){
            boolean Success = prepareBuild (7*x, 10*x, 1*x, 7*x);
            if (Success == true) {
                this.Archer += x;
                System.out.println ("Congratulations, you built " + x + " archer(s).");
            }
        }
        // To build a cavalry
        void buildCavalry (int x){
            boolean Success = prepareBuild (25*x, 30*x, 3*x, 25*x);
            if (Success == true) {
                this.Cavalry += x;
                System.out.println("Congratulations, you built " + x + " cavalry.");
            }
        }
        // To calculate defense
        void calcDefense (){
            Defense = Tower*10 + Archer*3 + Cavalry*2 + Soldier*1;
        }
        // To calculate power
        void calcPower (){
            Power = Cavalry*7 + Soldier*5 + Archer*2;
        }
        // To attack the other player
        void Attack (City city){
            if ((this.Power - city.Defense) > 0)
            {
                if (city.Wealth > this.Power - city.Defense)
                { city.Wealth = city.Wealth - (this.Power - city.Defense);
                  System.out.println("Your stats");
                  printer.printStats(this);
                  System.out.println("Enemy stats");
                  printer.printStats(this);
                  this.Archer = this.Archer / 2;
                  this.Cavalry = this.Cavalry / 2;
                  this.Soldier = this.Soldier / 2;
                } else
                {
                    city.Wealth = 0;
                    printer.printAll(this);
                    printer.printAll(city);
                    System.out.println("You win!");
                }
            } else
            {
                System.out.println("You do not have enough power to deal and damage.");
            }
        }
        // To end the turn
        void endTurn (){
            this.calcDefense();
            this.calcPower();
            System.out.println("End of your turn.");
            this.myTurn = false;
        }
        // To print all
        void printAll() {
            printer.printAll(this);
        }
        void printResources() {
            printer.printResources(this);
        }
        void printArmy() {
            printer.printArmy(this);
        }
        void printStats() {
            printer.printStats(this);
        }
        void printBuildings() {
            printer.printBuildings(this);
        }
    }
    Printer
    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package citygame12;
    
    /**
     *
     * @author Flying Bear
     */
    public class Printer {
    
        // To print everything
        void printAll (City city){
            this.printResources(city);
            this.printArmy(city);
            this.printStats(city);
            this.printBuildings(city);
        }
        // To print only resources
        void printResources (City city){
            System.out.println("Resources");
            System.out.println("Wood: " + city.Wood);
            System.out.println("Stone: " + city.Stone);
            System.out.println("Food: " + city.Food);
            System.out.println("Idle Population: " + city.Population);
        }
        // To print only Army
        void printArmy (City city){
            System.out.println("Army");
            System.out.println("Cavalry: " + city.Cavalry);
            System.out.println("Archer: " + city.Archer);
            System.out.println("Soldier: " + city.Soldier);
        }
        // To print only Stats
        void printStats (City city){
            System.out.println("Stats");
            System.out.println("Power: " + city.Power);
            System.out.println("Defense: " + city.Defense);
            System.out.println("Wealth: " + city.Wealth);
        }
        // To print only Buildings
        void printBuildings (City city){
            System.out.println("Buildings");
            System.out.println("Wood Mills: " + city.Woodmill);
            System.out.println("Stone Quarries: " + city.Stonequarry);
            System.out.println("Bakeries: " + city.Bakery);
            System.out.println("Houses: " + city.House);
            System.out.println("Towers: " + city.Tower);
            System.out.println("Banks: " + city.Bank);
        }
    }
    Reader
    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package citygame12;
    import java.io.*;
    
    /**
     *
     * @author Flying Bear
     */
    public class Reader {
        String userInput;
        int armyInput;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    
        void readInput() {
            try {
                            userInput = br.readLine();
                            }
                        catch (IOException ioe) {
                            System.out.println("Does not compute!");
                            }
        }
        void checkInput(City city, City othercity) {
            this.readInput();
            if (userInput.equalsIgnoreCase("build")) {
                this.buildInput(city);
            }
            else if (userInput.equalsIgnoreCase("print")) {
                this.printInput(city);
            }
            else if (userInput.equalsIgnoreCase("train")) {
                this.trainInput(city);
            }
            else if (userInput.equalsIgnoreCase("attack")) {
                this.attackInput(city, othercity);
            }
            else if (userInput.equalsIgnoreCase("end")) {
                this.endInput(city);
            }
            else System.out.println("Huh?");
        }
        void buildInput(City city) {
            System.out.println("Would you like to build a Stone Quarry(sq), Woodmill" +
                    "(wm), Bakery(b), House(h), Tower(t), or Bank($)?");
            this.readInput();
            if (userInput.equalsIgnoreCase("sq")) {
                city.buildStonequarry();
            }
            else if (userInput.equalsIgnoreCase("wm")) {
                city.buildWoodmill();
            }
            else if (userInput.equalsIgnoreCase("b")) {
                city.buildBakery();
            }
            else if (userInput.equalsIgnoreCase("h")) {
                city.buildHouse();
            }
            else if (userInput.equalsIgnoreCase("t")) {
                city.buildHouse();
            }
            else if (userInput.equalsIgnoreCase("$")) {
                city.buildBank();
            }
            else System.out.println("Huh?");
        }
        void printInput(City city) {
            System.out.println("Would you like to print all, resources, stats, or buildings?");
            this.readInput();
            if (userInput.equalsIgnoreCase("all")) {
                city.printAll();
            }
            else if (userInput.equalsIgnoreCase("resources")) {
                city.printResources();
            }
            else if (userInput.equalsIgnoreCase("stats")) {
                city.printStats();
            }
            else if (userInput.equalsIgnoreCase("buildings")) {
                city.printBuildings();
            }
        }
        void trainInput(City city) {
            System.out.println("Would you like to build archers(a), cavalry(c), or soldiers(s)?");
            this.readInput();
            if (userInput.equalsIgnoreCase("a")) {
                System.out.println("How many archers would you like to make?");
            try {
                            armyInput = br.read();
                            }
                        catch (IOException ioe) {
                            System.out.println("Does not compute!");
                            }
                city.buildArcher(armyInput);
            }
            else if (userInput.equalsIgnoreCase("c")) {
                System.out.println("How many cavalry would you like to make?");
            try {
                            armyInput = br.read();
                            }
                        catch (IOException ioe) {
                            System.out.println("Does not compute!");
                            }
                city.buildCavalry(armyInput);
            }
            else if (userInput.equalsIgnoreCase("s")) {
                System.out.println("How many soldiers would you like to make?");
            try {
                            armyInput = br.read();
                            }
                        catch (IOException ioe) {
                            System.out.println("Does not compute!");
                            }
                city.buildSoldier(armyInput);
            }
        }
        void attackInput(City city, City other) {
            this.readInput();
            if (userInput.equalsIgnoreCase("attack")) {
                city.Attack(other);
                city.endTurn();
            }
        }
        void endInput(City city) {
                city.endTurn();
            }
    }
    Last edited by Snoman; 07-26-2010 at 05:54 PM.

  10. #10
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    4

    Default

    BufferedReader.read() reads a single character (which also would screw up if you wanted 11 armies) and returns its keycode. Since you input "3", it returned "51", the ASCII code for it. (View Ascii Table - ASCII character codes and html, octal, hex and decimal chart conversion if you wish.) Instead, I would use readLine() and convert your result to an integer in a try/catch statement, and if it's not an integer prompt the user to enter again.

    Other than that, the code is looking good; but thing I noticed though (not sure if this is intended), but in the prepareBuild function, you do not subtract food after checking if you have enough.

    Looking good so far, though! Keep it up. :)

  11. #11
    Snoman is offline Member
    Join Date
    Jul 2010
    Posts
    9
    Rep Power
    0

    Default

    Thank you so much =)

    It works now.

    This is what I did, if there's a better way please tell me.
    Java Code:
        void convertString() {
            try {
                int armyInput = Integer.valueOf(userInput);
                armyIn = armyInput;
            }
            catch (NumberFormatException nfe) {
                System.out.println("Please enter an integer.");
            }
        }
    Java Code:
        void trainInput(City city) {
            System.out.println("Would you like to build archers(a), cavalry(c), or soldiers(s)?");
            this.readInput();
            if (userInput.equalsIgnoreCase("a")) {
                System.out.println("How many archers would you like to make?");
                this.readInput();
                this.convertString();
                city.buildArcher(armyIn);
            }
            else if (userInput.equalsIgnoreCase("c")) {
                System.out.println("How many cavalry would you like to make?");
                this.readInput();
                this.convertString();
                city.buildCavalry(armyIn);
            }
            else if (userInput.equalsIgnoreCase("s")) {
                System.out.println("How many soldiers would you like to make?");
                this.readInput();
                this.convertString();
                city.buildSoldier(armyIn);
            }
            else System.out.println("Huh?");
        }

  12. #12
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    4

    Default

    I would put this.readInput() in the convertString() function, since it's always called before convertString anyway. If you put it inside, you don't have to remember to call it each time.

    Otherwise, it's good. GL!

    PS: Also, loop it so they can reenter the integer.
    Last edited by Zack; 07-26-2010 at 08:30 PM.

  13. #13
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    your City class is too long and filled with methods etc that break its abstraction i.e deviate away from what a City is.

    e.g.
    Java Code:
    // Resources in a city
        int Wood = 300;
        int Stone = 150;
        int Food = 50;
        int Population = 10;
    make a resource class instead

    Java Code:
        // Army of a city
        int Cavalry = 0;
        int Archer = 0;
        int Soldier = 0;
        // Stats of a city
        int Power;
        int Defense;
    make an army class instead

    why would a City class have a start turn
    Java Code:
    // To start the turn
        void startTurn (){
            System.out.println("Start of your turn.");
            this.Wood = this.Wood + (this.Woodmill*20);
            this.Stone = this.Stone + (this.Stonequarry*20);
            this.Wealth = this.Wealth + (this.Bank*10);
            this.Food = this.Food + (this.Bakery*15);
            this.calcPower();
            this.calcDefense();
            this.myTurn = true;
        }
    very quick tip, when making a class, always ask yourself is what I am putting into the class consistent with what the class should do? For e.g. when making a method inside a class ask yourself, this type of class has a ?
    A City has a turn? no.
    A City has an army? Probably, but is army made up of so many elements that City by itself is getting lost? i.e. is army taking up most of City implementation? time for an army class....

    Another quick guideline but not unbreakable, keep class fields limited to about 7 and methods about the same, anything over this is screaming for additional classes most likely.

  14. #14
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    4

    Default

    Quote Originally Posted by al_Marshy_1981 View Post
    very quick tip, when making a class, always ask yourself is what I am putting into the class consistent with what the class should do? For e.g. when making a method inside a class ask yourself, this type of class has a ?
    Quote Originally Posted by al_Marshy_1981 View Post
    Another quick guideline but not unbreakable, keep class fields limited to about 7 and methods about the same, anything over this is screaming for additional classes most likely.
    While I agree with the first statement, I think the second one may be a bad one to follow. In a game I am working on, many many classes have more than seven fields (some as many as 20; owners, targets, etc.), and numerous more methods. But, to each his own; if this little guide works for you, then by all means use it.

  15. #15
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    Quote Originally Posted by Zack View Post
    While I agree with the first statement, I think the second one may be a bad one to follow. In a game I am working on, many many classes have more than seven fields (some as many as 20; owners, targets, etc.), and numerous more methods. But, to each his own; if this little guide works for you, then by all means use it.
    Like I said it is not unbreakable, just something to be strived for, scientifically it has been proved that keeping track of more than 7 methods becomes too complex.

  16. #16
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    Quote Originally Posted by al_Marshy_1981 View Post
    Another quick guideline but not unbreakable, keep class fields limited to about 7 and methods about the same, anything over this is screaming for additional classes most likely.
    hunts desperately within the standard libraries for such a class... :p
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  17. #17
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    Having completed my 'poke fun at statements' quota for today, I will endeavor to give some useful input.

    Splitting classes up is good. I'm currently writing a program for a strategy game where units have to track their health, what movement they're going to make, what shots they'll fire, etc. If I tried to do that in one class, it'd be a nightmare. Instead, I have 3 classes - HealthTracker, MoveTracker, and ShotTracker. Its a lot easier to work with :) So, you'll probably want to create an Army class and a Resources class.

    Also, is a city a player? In answer to al's question about city's having turns: No, but player's do, and the cities are currently being treated as players. Also, does a city hold resources, or will it be a player-based value. Either works, for my program it's city-based, but for many games it's player-based, and you will need to decide if you ever let a player have multiple cities.

    Finally, when asking for input, the best bet is to have a simple 'help' command, that prints out a message telling the user what input is accepted, rather than trying to cram it all into the prompt. You can do both, but the prompts just seem rather long.

    Other than those three things, it looks great. Keep going with it, its a great thing to work with because there are so many things you can add to learn about different APIs and such. (A few things you could add in the future - multiplayer using client-server/peer-to-peer, gui, saved games, and more. Remember to write smaller programs using each part first though.)
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  18. #18
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    4

    Default

    While encouraging splitting up classes is good, be wary of going too far with it. Boyo suggested having a Resources class, but personally I would not do this.

    Here are the conditions that must be met for me to create a new class:
    1. The existing class(es) must either be too large to add more methods and variables, or they must not encapsulate the new class's purpose.
    2. The new class must have both methods and variables. (Caveat to this: Static method class may not have variables; and an Enum class will not necessarily have methods.)
    3. The methods and variables in the new class must be used by another class.

    In this case, a Resources class would not satisfy the second criterion. Unless you have a prepareBuild() method in there (which fits better into City than Resources), it would have no methods.

    But you have lots of good advice here; it's up to you what you do now. Personal preference is everything in programming. Best of luck! :)

  19. #19
    demonaz is offline Member
    Join Date
    Jul 2010
    Posts
    1
    Rep Power
    0

    Thumbs up

    Quote Originally Posted by Zack View Post
    One thing I just thought I'd mention... you may or may not have noticed this as well, Snoman, but it's worth showing you.

    Java Code:
        void buildWoodmill (){
            if (this.Wood >= 50)
            {
                if (this.Stone >= 25)
                {
                    if (this.Population >= 3)
                    { this.Woodmill = this.Woodmill + 1;
                      this.Wood = this.Wood - 50;
                      this.Stone = this.Stone - 25;
                      this.Population = this.Population - 3;
                      System.out.println("Congratulations, you built a wood mill.");
                    } else
                    {
                        System.out.println("You don't have enough population.");
                    }
                } else
                {
                    System.out.println("You don't have enough stone.");
                }
            } else
            {
                System.out.println("You don't have enough wood.");
            }
        }
    You'll find that in all your build*() functions, this is pretty standard. You could do something like this instead:

    Java Code:
    boolean prepareBuild(int RequiredWood, int RequiredStone, int RequiredPopulation) {
    	if (this.Wood < RequiredWood) {
    		System.out.println("You don't have enough wood.");
    		return false;
    	}
    	if (this.Stone < RequiredStone) {
    		System.out.println("You don't have enough stone.");
    		return false;
    	}
    	if (this.Population < RequiredPopulation) {
    		System.out.println("You don't have enough population.");
    		return false;
    	}
    	this.Wood -= RequiredWood;
    	this.Stone -= RequiredStone;
    	this.Population -= RequiredPopulation;
    	return true;
    }
    Now your other functions look like this:
    Java Code:
    void buildWoodmill() {
    	boolean Success = prepareBuild(50,25,3));
    	if (Success == true) {
    		this.Woodmill++;
    		System.out.println("Congratulations, you built a wood mill.");
    	}
    }
    void buildHouse() {
    	boolean Success = prepareBuild(50,50,0));
    	if (Success == true) {
    		this.House++;
    		System.out.println("Congratulations, you built a house.");
    	}
    }
    void buildTower() {
    	boolean Success = prepareBuild(30,70,3));
    	if (Success == true) {
    		this.Tower++;
    		System.out.println("Congratulations, you built a tower.");
    	}
    }

    Just a suggestion; if you don't like it don't use it--but it's much preferred if working with groups of people and code modifications (i.e. in the future, if you need to add something other than Wood and Stone, for example).
    That was enlightening =).

  20. #20
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    Quote Originally Posted by Zack View Post
    Here are the conditions that must be met for me to create a new class:
    1. The existing class(es) must either be too large to add more methods and variables, or they must not encapsulate the new class's purpose.
    2. The new class must have both methods and variables. (Caveat to this: Static method class may not have variables; and an Enum class will not necessarily have methods.)
    3. The methods and variables in the new class must be used by another class.

    In this case, a Resources class would not satisfy the second criterion. Unless you have a prepareBuild() method in there (which fits better into City than Resources), it would have no methods.
    Personally, I might put a prepareBuild method into a Resources class, but with a different name. Also, in C/C# it would be a struct (and C++ for me, but C++ structs are really just classes that default to public for member visibility) but java has no equivalent, so a class it must be. However, as you mentioned (though not in the quote) it is personal preference. Just thought I'd add some more input about what my choice would be.
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

Page 1 of 2 12 LastLast

Similar Threads

  1. Keep my TCP connection alive
    By eggmanpete in forum Advanced Java
    Replies: 4
    Last Post: 03-02-2009, 06:11 AM
  2. How to configure "keep alive" in Sockets?
    By rajdotme in forum Networking
    Replies: 1
    Last Post: 04-16-2008, 11:36 PM

Posting Permissions

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