Results 1 to 11 of 11
  1. #1
    Leeish is offline Member
    Join Date
    Sep 2011
    Posts
    11
    Rep Power
    0

    Default Dynamically Refer to Objects/Variables

    It's hard for me to reference/search for topics as I am not sure if I am using the correct lingo, etc. I am used to PHP and trying to pick up Java as well. The problem I have may be solved by reflecting or something I did read a bit, but I am asking is there is A: a better way or B: a solution to my way of thinking.

    I am setting up a board game for practice. It's a game played with Marbles similar to Sorry. That's the easiest way to explain it.

    I've set up a class of objects for Marbles (play pieces), Dice, Players, Colors, and the Board. (These might not be the best classes, but so far it's working.)

    The Player objects each have four Marble objects and a Color Enum. The Dice is an object that essentially runs a method to return a random 1-6 number. All of that is set up to my liking and I've tested the code I can initiate the players, roll the dice, move the marbles. My problem comes in locating the marbles on the board.

    At first I wanted to have the Board object have an array of integers as a field, essentially it's locations on itself. But I got to thinking that the locations should actually be objects themselves with boolean values that can be occupied or not occupied. That way when the die is rolled and the move marble method is called, it can check the Board object and see if the space is occupied or not.

    There in lies the problem. I don't mind writing out 65 location objects within the board itself. I'd rather do it in a loop, but can't figure out how to dynamically create object names. However before I started writing them out I got to looking at my moveMarble code. For now it's just simply:

    Java Code:
    public void movePiece(int a){this.location = this.location + a;}
    location right now is an int, but I need to make it an object that can be occupied/unoccupied as stated above. If I go and create 65 objects and one of them is named location1, how can I reference that dynamically withing the movePiece statement. What I want to do it this:

    Java Code:
    public void movePiece(int a, int newLocation){
    int X = newLocation;
    if(this.LocationX.occupied == true) {
    //run code if space is occupied
    } else {
    this.location = this.location + a;
    }
    }
    Where x is the space the piece happened to land on. I added the X = newLocation just to be clear, I know it's not necessary.

    If this isn't the best method, what method should I use to track the if the locations on the board are occupied or not. Creating a Location object for each spot and making these objects members of the board seems like the most logical solution.

    Thanks ahead of time.

  2. #2
    Petr's Avatar
    Petr is offline Senior Member
    Join Date
    Jan 2011
    Location
    Russia
    Posts
    618
    Rep Power
    4

    Default Re: Dynamically Refer to Objects/Variables

    Hi, It is easy. You can create an one object and just get it in any place in your code. For it you can use singleton pattern.
    Skype: petrarsentev
    http://TrackStudio.com

  3. #3
    Leeish is offline Member
    Join Date
    Sep 2011
    Posts
    11
    Rep Power
    0

    Default Re: Dynamically Refer to Objects/Variables

    Java Code:
    public class Singleton {
            private static final Singleton instance = new Singleton();
     
            // Private constructor prevents instantiation from other classes
            private Singleton() { }
     
            public static Singleton getInstance() {
                    return instance;
            }
    }
    Are you saying it should be:

    Java Code:
    public class Location{
            private static final Location instance = new Location();
     
            // Private constructor prevents instantiation from other classes
            private Location() { }
     
            public static LocagetInstance() {
                    return instance;
            }
    }
    From what I read this only initiates the instance when it is referenced or something. I am not sure that would work. I need more than one object. I feel like I either need 65 different Location objects, or a single array like: Location[] locations = new Location[65]; and then for each locations[n] would have a location[n].occupied = true/false. I was trying to use this method but I couldn't figure out how to access the members in locations[n].

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

    Default Re: Dynamically Refer to Objects/Variables

    Quote Originally Posted by Leeish View Post
    It's hard for me to reference/search for topics as I am not sure if I am using the correct lingo, etc. I am used to PHP and trying to pick up Java as well. The problem I have may be solved by reflecting or something I did read a bit, but I am asking is there is A: a better way or B: a solution to my way of thinking.
    This may be part of your problem in that when you program in Java you need a different mind-set then when coding in PHP. Neither is right and neither is wrong, but they're each often wrong for the other as your problem illustrates.


    At first I wanted to have the Board object have an array of integers as a field, essentially it's locations on itself. But I got to thinking that the locations should actually be objects themselves with boolean values that can be occupied or not occupied. That way when the die is rolled and the move marble method is called, it can check the Board object and see if the space is occupied or not.

    There in lies the problem. I don't mind writing out 65 location objects within the board itself. I'd rather do it in a loop, but can't figure out how to dynamically create object names. However before I started writing them out I got to looking at my moveMarble code. For now it's just simply:

    Java Code:
    public void movePiece(int a){this.location = this.location + a;}
    location right now is an int, but I need to make it an object that can be occupied/unoccupied as stated above. If I go and create 65 objects and one of them is named location1, how can I reference that dynamically withing the movePiece statement. What I want to do it this:

    Java Code:
    public void movePiece(int a, int newLocation){
    int X = newLocation;
    if(this.LocationX.occupied == true) {
    //run code if space is occupied
    } else {
    this.location = this.location + a;
    }
    }
    Where x is the space the piece happened to land on. I added the X = newLocation just to be clear, I know it's not necessary.

    If this isn't the best method, what method should I use to track the if the locations on the board are occupied or not. Creating a Location object for each spot and making these objects members of the board seems like the most logical solution.

    Thanks ahead of time.
    With PHP you may dynamically create variable names, but you don't with Java, nor do you need to or want to. Instead I would use either an array of Location objects or some other collection such as a HashMap or ArrayList of Location. In Java variable names are not as important as you think and in fact almost don't exist in the compiled code. What is important is that you have a logical way to get a reference to the object you're after.

    And definitely don't use singletons for any of this. They are not needed and in fact bad practice for this type of program.

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

    Default Re: Dynamically Refer to Objects/Variables

    Also, while you may call the move method of Piece, the Piece object will likely communicate this to the Game object perhaps calling requestMove(...) to the Game object. It will then check its Location array, see where Piece is, see if it can move it to the new location, and if so move it.

  6. #6
    Leeish is offline Member
    Join Date
    Sep 2011
    Posts
    11
    Rep Power
    0

    Default Re: Dynamically Refer to Objects/Variables

    I am pretty sure my setup of where some of these methods are located and how they interact with each other via interfaces will change. For now I am more worried about getting logic and setup functionality. Probably not the best way to setup a project, but I am working with what I know.

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

    Default Re: Dynamically Refer to Objects/Variables

    Quote Originally Posted by Leeish View Post
    I am pretty sure my setup of where some of these methods are located and how they interact with each other via interfaces will change. For now I am more worried about getting logic and setup functionality. Probably not the best way to setup a project, but I am working with what I know.
    I don't understand what you mean by this post. Are you asking a question or asking for clarification?

  8. #8
    Leeish is offline Member
    Join Date
    Sep 2011
    Posts
    11
    Rep Power
    0

    Default Re: Dynamically Refer to Objects/Variables

    No, you were talking about how the piece will likely communicate with the game obj, etc. I was just clarifying that I may not have the exact setup of how things will communicate with what correctly. Unimportant.

    So, tell me then why this method won't work. I have the following class:

    Java Code:
    public class Locations{
            int number;
            String type;
            boolean occupied = false;
            
            public Locations(int value, String a){
                number = value;
                type = a;
            }
            public void changeState(boolean change){
                this.occupied = change;
            }
        }
    Then on my Board object. When i am setting up the game board, I want to crate 65 different locations objects. 60 are regular, 4 are fasttrack, and there are 4 that are in the center. Don't worry about the logic there, just know that is what the type is for.

    Java Code:
    public class Board {
        Locations[] locations = new Locations[65];
    
    //I have more code here that contains a loop. Where I want to setup each Location obj and I am calling then like this:
    Locations locations[i] = new Locations(counter, "REG");
    I can't figure out how to create each Locations object within the locations array. Does that make sense?

  9. #9
    Leeish is offline Member
    Join Date
    Sep 2011
    Posts
    11
    Rep Power
    0

    Default Re: Dynamically Refer to Objects/Variables

    I think I figured it out maybe. My understanding was that when I called:

    Java Code:
    Locations[] locations = new Locations[65];
    This created an array called locations that reserved memory for 65 spaces in that array to hold location objects. I would later have to create those objects and reference them in the array.

    However the code that just worked was:

    Java Code:
    locations[i].setupLocation(counter, "REG");
    Where I created a setupLocation method to match my previous constructor. I am confused why this works. I don't see where I ever used the constructor to make each object referenced in the array. My constructor in the Locations class is:

    Java Code:
    public Locations(int value, String a){
                number = value;
                type = a;
            }
    How in the world is java letting me ignore the arguments in the constructor when I first created the Locations array? Can I pass them in a manner as follows:
    Java Code:
    Locations[] locations = new Locations[65](args);
    I guess that wouldn't make sense because that would be the same as just setting the default field values in the class itself.

    Am I understanding correctly. If this is the case then I guess I figured it out.

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

    Default Re: Dynamically Refer to Objects/Variables

    It shouldn't be ignoring the constructor. If you run the code, you should be getting a NullPointerException for the very reasons you mention. I would use an enum for type rather than a String myself. Something like:

    Java Code:
    import java.util.ArrayList;
    import java.util.List;
    
    public class Board {
       List<Location> locations = new ArrayList<Location>();
    
       public Board() {
          int counter = 0;
          for (LocationType lType : LocationType.values()) {
             for (int i = 0; i < lType.getMaxCount(); i++) {
                Location location = new Location();
                location.setupLocation(counter, lType);
                locations.add(location);
                counter++;
             }
          }
       }
       
       public void showLocations() {
          for (Location location : locations) {
             System.out.println(location);
          }
       }
    
       public static void main(String[] args) {
          Board board = new Board();
          board.showLocations();
       }
    }
    
    class Location {
       int number;
       LocationType type;
       boolean occupied = false;
    
       public Location() {
       }
       
       Location(int value, LocationType type) {
          this.number = value;
          this.type = type;
       }
    
       public void setupLocation(int value, LocationType a) {
          number = value;
          type = a;
       }
    
       public void changeState(boolean change) {
          this.occupied = change;
       }
    
       @Override
       public String toString() {
          return String.format("Location, Type: %s, Number: %d, Occupied: %b",
                type, number, occupied);
       }
    }
    
    enum LocationType {
       REGULAR(60), FAST_TRACK(4), CENTER(4);
    
       private int maxCount;
    
       private LocationType(int maxCount) {
          this.maxCount = maxCount;
       }
    
       public int getMaxCount() {
          return maxCount;
       }
    }
    Also, my count suggests that the array needs to hold 68 Location objects. I use an ArrayList and sort of avoid the issue.

  11. #11
    Leeish is offline Member
    Join Date
    Sep 2011
    Posts
    11
    Rep Power
    0

    Default Re: Dynamically Refer to Objects/Variables

    You code probably compresses what I got here, or maybe does it in a different way. I did get a NullPointer because the objects were never created but referenced correctly.

    Java Code:
    public class Locations{
            int number;
            String type;
            boolean occupied = false;
            
            public Locations(){
            }
            public void setupLocation(int value, String a){
                number = value;
                type = a;
            }
            public void changeState(boolean verify){
                this.occupied = verify;
            }
        }
    public class Board {
        Locations[] locations = new Locations[64];
        int counter = 1;
        int fast = 5;
        public Board(){
            for(int i = 0;i<64;i++){
                if (i == fast){
                    locations[i] = new Locations();
                    locations[i++].setupLocation(counter, "FAST");
                    locations[i] = new Locations();
                    locations[i].setupLocation(counter+1, "CEN");
                    fast = fast+16;
                    counter++;
                } else if(i == fast+16){
                    locations[i] = new Locations();
                    locations[i++].setupLocation(counter, "FAST");
                    locations[i] = new Locations();
                    locations[i].setupLocation(counter+1, "CEN");
                    fast = fast+16;
                    counter++;
                } else if (i != fast && i != fast+16) {
                    //regSpaces[i] = counter;
                    locations[i] = new Locations();
                    locations[i].setupLocation(counter, "REG");
                    counter++;
                }
            }
        }
        public void boardCheck(){
            for(int i = 0;i<64;i++){
                System.out.println("Location "+locations[i].number+" is a "+locations[i].type);
            }
        }
    //The check results in:
    Location 1 is a REG
    Location 2 is a REG
    Location 3 is a REG
    Location 4 is a REG
    Location 5 is a REG
    Location 6 is a FAST
    Location 7 is a CEN
    Location 7 is a REG
    Location 8 is a REG
    Location 9 is a REG
    Location 10 is a REG
    Location 11 is a REG
    Location 12 is a REG
    Location 13 is a REG
    Location 14 is a REG
    Location 15 is a REG
    Location 16 is a REG
    Location 17 is a REG
    Location 18 is a REG
    Location 19 is a REG
    Location 20 is a REG
    Location 21 is a FAST
    Location 22 is a CEN
    Location 22 is a REG
    Location 23 is a REG
    Location 24 is a REG
    Location 25 is a REG
    Location 26 is a REG
    Location 27 is a REG
    Location 28 is a REG
    Location 29 is a REG
    Location 30 is a REG
    Location 31 is a REG
    Location 32 is a REG
    Location 33 is a REG
    Location 34 is a REG
    Location 35 is a REG
    Location 36 is a FAST
    Location 37 is a CEN
    Location 37 is a REG
    Location 38 is a REG
    Location 39 is a REG
    Location 40 is a REG
    Location 41 is a REG
    Location 42 is a REG
    Location 43 is a REG
    Location 44 is a REG
    Location 45 is a REG
    Location 46 is a REG
    Location 47 is a REG
    Location 48 is a REG
    Location 49 is a REG
    Location 50 is a REG
    Location 51 is a FAST
    Location 52 is a CEN
    Location 52 is a REG
    Location 53 is a REG
    Location 54 is a REG
    Location 55 is a REG
    Location 56 is a REG
    Location 57 is a REG
    Location 58 is a REG
    Location 59 is a REG
    Location 60 is a REG
    I don't know the ins and outs of short cutting some of the code, but I think this works. For each locations[x] x = placeOnBoard -1. But that is to be expected with arrays. The reason a Center space shares the same value as a reg space is because when you land on the fast track which rings the center of the board, it's only one more move to jump to the center. You have the option in the game if you roll an exact number to the center to go to the center or to go around normally. I'll have to have a static occupied variable for center spaces maybe but for the setup of Location objects I guess this pretty much works.

    I'll dig through your code and try to understand it. Thanks.

Similar Threads

  1. Identifying Objects/Variables
    By hiralarious in forum New To Java
    Replies: 2
    Last Post: 09-20-2011, 03:44 AM
  2. Dynamically create objects, set value and call
    By buntyindia in forum New To Java
    Replies: 5
    Last Post: 05-25-2011, 05:59 PM
  3. Replies: 3
    Last Post: 03-15-2011, 06:49 PM
  4. Replies: 1
    Last Post: 01-03-2010, 09:48 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
  •