ulrail.gif

HW J8: 2-D Arrays

  ur-2c.gif urrail.gif
blrail-nonavbar.gif

Home | Resources | Homeworks | Exams
Slides | Labs | Contacts | Submit | TAs

br-2a.gif   br-2c.gif brrail.gif
spacer.gif spacer.gif spacer.gif

Purpose

A multi-dimensional array is an important data structure that is suitable for many programming situations. In this assignment, you will gain experience designing and implementing a 2-dimensional array. These experiences can be readily generalized to arrays with more than only 2 dimensions.  This new programming capability can be valuable as you design and develop programs in the future.

The second purpose of this assignment is to complete the Trader game design and implementation. Only one more class needs to be designed and implemented: the Universe class.

This assignment creates a new flexibility because of the Descriptions class and the Map class, which you designed and implemented in the last few labs. The Descriptions class provides the capability to randomly choose such properties as the Location names, the adjective describing each Location, and the Cargo names and cost factors. The important capability that the Map provides is to print out the Universe, noting where the user currently is. We will exploit each of these as we create the Universe class to complete our game. 

Files

To get started, create a new directory called HWJ8, and download Universe.java, Market.class, Location.class, Inventory.class, Map.class, Vehicle.class Cargo.class, Parser.class, and Game.java (right click on each link, select "save as", and save them all to this directory). Note that in this assignment the only file you should modify is Universe.java. As with the previous assignments, you are free (and even encouraged) to use your versions of the previous Java classes (e.g., Market, Location, Inventory, Map, Vehicle, Cargo, Parser) using the technique described in the last homework assignment. Make sure that when you're done either downloading or copying your own versions to this directory, you have all 9 of the above Java classes (either source code or bytecode) in this directory.

You should use your own Descriptions.java file, as that will allow your Universe to have the names you came up with in lab 10.  If you do not have it (or it doesn't work), you can download ours here. Remember, if you use your Descriptions.java file, then the CORRECT implementation of 'getCargoCostFactor' must use '.equals' instead of '==' for the string comparison.

Note that the Java documentation for all of the existing classes can be found here.

There is a remaining HW J7 issue that a lot of people ran into, and will manifest itself in this assignment as well.  If you are using our Location.class file above, then you can skip this paragraph; if you are using yours, definitely read this paragraph.  In HW J7, our intent with the Inventory class was to create a Cargo array of Game.MAX_INVENTORY_SIZE (currently set to 15), but only put Game.DEFAULT_INVENTORY_SIZE (currently 5) Cargo objects in the inventory.  If you use the same value for the array size and the number of Cargo elements in it, then you can never sell an item in a Market (as their inventory is always full).  This wasn't explained very well in HW J7....

Universe class

The Universe is used to represent the Locations that the Vehicle can travel to in order to buy and sell goods. Note that we could (and have) encoded these locations as a list (Vector), but a 2-dimensional array is a better representation, in part because a 2-dimensional array is intuitively a better fit.

You might be asking yourself, "Didn't we define a 2-D array as part of Lab 11 on the Map class? Why are we doing it again?"  This is not the case.  In Lab 11, we assumed that a particular 2-D array already existed, and we performed operations on it.  That is, in Lab 11, we did not define the array itself, but used the methods from the Universe class instead.  This is the assignment where we actually define the array in this Universe class.

Attributes
  • universe (Location[][]): The data structure that contains the Locations of the Universe, indexed by (row,col) coordinates
     
  • density (double):  Roughly, this is the probability that a Location exists at a particular X-Y coordinate of the Universe. Note that the semantics of this field is that if a given Universe has a density of "0.1", then it is NOT necessary that precisely 10% of the coordinates contain an actual instance of a Location.  This is like saying that if I flip a coin 100,000 times, then "heads" will come up approximately 50,000 times. But if I flip a coin only 4 times, then it's possible that "heads" would happen twice, although I shouldn't be surprised if I get three "heads".

Accessors/Mutators

Of course, these instance variables in this class should be declared private and manipulated via accessor and mutator methods as we have discussed during lecture.  Thus, you must include an accessor and mutator method for each of the above fields in both classes.  The name of the accessor/mutator should follow the standard Java naming conventions (i.e. getPosX(), setName(), etc.).  All the mutators must check for invalid values being passed in -- what you do when you find an invalid value is your choice (print an error message, not change the value, etc.).

Other methods

The location class should also support the following methods:

  • Universe (): The default constructor, it initializes the Universe to default values.  The default for the height, width, and density are constants in the Game class (UNIVERSE_HEIGHT, UNIVERSE_WIDTH, and UNIVERSE_DENSITY).  Note that the constructors do NOT put Location objects in the Universe -- this is done via the populate() method.
     
  • Universe (int theHeight, int theWidth, double theDensity): The specific constructor initializes the density to the passed value.  This method also initializes the universe array to the passed dimensions.  Note that since the array is indexed by (row,col) coordinates, then this method should create the array of size (theHeight, theWidth).  Note that the constructors do NOT put Location objects in the Universe -- this is done via the populate() method.  Note that Game.java calls the specific constructor, and creates a universe that is 10 columns wide by 12 rows high -- if yours is 12x10, then something is wrong.
     
  • int getNumCols(): this method returns the number of columns (i.e. the width) of the Universe.  It should determine this by the dimensions of the 2-D universe array.  If you forget how to do this, see slide 80 in the lecture notes on arrays.
     
  • int getNumRows(): this method returns the number of rows (i.e. the height) of the Universe.  It should determine this by the dimensions of the 2-D universe array.  If you forget how to do this, see slide 80 in the lecture notes on arrays.
     
  • void populate(): This method will fill the universe array with locations.  For each spot in the 2-D array, the chance of having a Location at that spot is density.  So if density is 0.1, then there is a 10% change that each spot has a location.  You can obtain a random number via Game.rand.nextDouble().  Thus, for each spot in the 2-D array, obtain a random number via Game.rand.nextDouble().  If that random number is less than density, then that spot should hold a new Location; otherwise, it should hold null.

    Note that if your universe is too large (for example, if you change the size of the the universe's height and width in Game.java), and thus the populate() method tries to create more Locations than there are names in Descriptions.getLocation(), then your Game.java will hang in an infinite loop -- so don't create too large a universe (you can experimentally determine roughly the threshold for "too large").  If a Location is to be at a given spot, the following are the values for that Location (in other words, the parameters to the invocation of the constructor):
     
    • The name is from Descriptions.getLocationName(), but must be unique -- meaning one that does not exist already.  So you need to check if the name exists already (if so, get a new one).  You should use the findLocationByName() method for this.  The createUniqueInventory() method in the Market class does something similar (in that case, it creates unique cargo names).
    • The appearance is determined by Descriptions.getAppearance(). It's okay if multiple Locations in the universe have the same appearance.
    • The row and col coordinates are for the particular position in the 2-D array.
    • The location's market should be created with a random cost factor that is between 0.0 and Game.MAX_COST_FACTOR (obviously, the cost factor can't be 0.0 itself).
       
  • void setLocationAt (int row, int col, Location loc): This method sets the location at (row, col) to the passed Location value.
     
  • Location getLocationAt (int row, int col): Returns the Location at the coordinates (row,col). If no such Location exists, then null is returned.
     
  • Location getRandomLocation(): Chooses and returns one of Locations in the Universe at random.  An easy way to do this is to add all the locations into a vector, shuffle the vector (via Collections.shuffle()), and then return the first element in that vector.
     
  • Location findLocationByName(String dest): This method looks through all of the Locations in the Universe until finding the one with the name "dest". If no such named Location exists, returns null.

Final Version of the Game

Here is a sample output. The input that the user entered is shown in red.  Note that this output only deals with traveling from one location to another.  The other aspects of the game (buying and selling goods, etc.) aren't shown below. 

Welcome to CS101 Space Trader v4!

Your InterGallactic Thunderbird is starting at Higgin's Moon (8.0,9.0).
You burn fuel at the rate of 5.00 gozorkas per million kilometers.

You are at a Higgin's Moon
You have $1,000.00 on hand
Valid commands are:
        travel (to travel to another location)
        market (to enter the market)
        worldmap (to print out the map)
        inventory (to show your inventory)
        quit (to leave the game)
You can abbreviate any command by its first letter
Enter next command: t

Printing Universe
1       -       -       -       -       -       -       -       -       -

2       -       -       3       -       4       -       -       -       -

-       -       -       -       -       -       -       -       -       5

-       -       -       -       -       -       -       -       -       6

-       -       -       -       -       7       -       -       8       -

-       -       -       -       -       9       -       -       -       10

-       -       -       -       -       -       -       -       -       -

-       11      -       -       -       12      -       -       -       -

-       -       -       -       -       -       13      -       -       14

-       -       -       -       -       -       -       -       -       -

-       -       -       -       -       15      -       -       -       -

16      -       -       17      -       -       -       -       -       -


The valid destinations are:
1: Newhall
2: Muir
3: Heinlein
4: Ezra
5: Boros
6: Londinium
7: Hera
8: Triumph
9: Sihnon
10: Osiris
11: Santo
12: Athens
13: Beylix
14: Higgin's Moon (your location)
15: Bernadette
16: St. Albans
17: Regina
Enter the name of the destination you want to travel to: Triumph
This is a distance of 4.12 million kilometers
This will require 20.62 gozorkas of fuel
You have 1,000.00 gozorkas of fuel on board
You travel to Triumph
You have 979.38 gozorkas of fuel on board

You are at a Triumph
You have $1,000.00 on hand
Valid commands are:
        travel (to travel to another location)
        market (to enter the market)
        worldmap (to print out the map)
        inventory (to show your inventory)
        quit (to leave the game)
You can abbreviate any command by its first letter
Enter next command: m

Welcome to the market at Triumph (4.0,8.0).  The cost factor here is 0.10

You are at the market.  You have $1,000.00 on hand
Valid commands are:
        buy (to buy cargo)
        sell (to sell cargo)
        available (to see what's available to buy)
        inventory (to show your inventory)
        exit (to exit the market and return to the location)
Enter next command: b

Possible items to trade:
0: 4 units of Aluminum at $0.02 per unit (total price in market: $0.06)
1: 3 units of Gold at $0.90 per unit (total price in market: $2.70)
2: 4 units of Medicine at $2.50 per unit (total price in market: $10.02)
3: 7 units of Java textbooks at $30.91 per unit (total price in market: $216.35)

4: 8 units of Waste at $0.72 per unit (total price in market: $5.75)
Which one do you want to trade? 0
It will cost $0.06 for this purchase

You are at the market.  You have $999.94 on hand
Valid commands are:
        buy (to buy cargo)
        sell (to sell cargo)
        available (to see what's available to buy)
        inventory (to show your inventory)
        exit (to exit the market and return to the location)
Enter next command: b

Possible items to trade:
0: 3 units of Gold at $0.90 per unit (total price in market: $2.70)
1: 4 units of Medicine at $2.50 per unit (total price in market: $10.02)
2: 7 units of Java textbooks at $30.91 per unit (total price in market: $216.35)

3: 8 units of Waste at $0.72 per unit (total price in market: $5.75)
Which one do you want to trade? 0
It will cost $2.70 for this purchase

You are at the market.  You have $997.24 on hand
Valid commands are:
        buy (to buy cargo)
        sell (to sell cargo)
        available (to see what's available to buy)
        inventory (to show your inventory)
        exit (to exit the market and return to the location)
Enter next command: b

Possible items to trade:
0: 4 units of Medicine at $2.50 per unit (total price in market: $10.02)
1: 7 units of Java textbooks at $30.91 per unit (total price in market: $216.35)

2: 8 units of Waste at $0.72 per unit (total price in market: $5.75)
Which one do you want to trade? 0
It will cost $10.02 for this purchase

You are at the market.  You have $987.22 on hand
Valid commands are:
        buy (to buy cargo)
        sell (to sell cargo)
        available (to see what's available to buy)
        inventory (to show your inventory)
        exit (to exit the market and return to the location)
Enter next command: e

You are at a Triumph
You have $987.22 on hand
Valid commands are:
        travel (to travel to another location)
        market (to enter the market)
        worldmap (to print out the map)
        inventory (to show your inventory)
        quit (to leave the game)
You can abbreviate any command by its first letter
Enter next command: t

Printing Universe
1       -       -       -       -       -       -       -       -       -

2       -       -       3       -       4       -       -       -       -

-       -       -       -       -       -       -       -       -       5

-       -       -       -       -       -       -       -       -       6

-       -       -       -       -       7       -       -       8       -

-       -       -       -       -       9       -       -       -       10

-       -       -       -       -       -       -       -       -       -

-       11      -       -       -       12      -       -       -       -

-       -       -       -       -       -       13      -       -       14

-       -       -       -       -       -       -       -       -       -

-       -       -       -       -       15      -       -       -       -

16      -       -       17      -       -       -       -       -       -


The valid destinations are:
1: Newhall
2: Muir
3: Heinlein
4: Ezra
5: Boros
6: Londinium
7: Hera
8: Triumph (your location)
9: Sihnon
10: Osiris
11: Santo
12: Athens
13: Beylix
14: Higgin's Moon
15: Bernadette
16: St. Albans
17: Regina
Enter the name of the destination you want to travel to: Londinium
This is a distance of 1.41 million kilometers
This will require 7.07 gozorkas of fuel
You have 979.38 gozorkas of fuel on board
You travel to Londinium
You have 972.31 gozorkas of fuel on board

You are at a Londinium
You have $987.22 on hand
Valid commands are:
        travel (to travel to another location)
        market (to enter the market)
        worldmap (to print out the map)
        inventory (to show your inventory)
        quit (to leave the game)
You can abbreviate any command by its first letter
Enter next command: m

Welcome to the market at Londinium (3.0,9.0).  The cost factor here is 1.00

You are at the market.  You have $987.22 on hand
Valid commands are:
        buy (to buy cargo)
        sell (to sell cargo)
        available (to see what's available to buy)
        inventory (to show your inventory)
        exit (to exit the market and return to the location)
Enter next command: s

Possible items to trade:
0: 4 units of Aluminum at $0.16 per unit (total price in market: $0.63)
1: 3 units of Gold at $9.05 per unit (total price in market: $27.15)
2: 4 units of Medicine at $25.23 per unit (total price in market: $100.92)
Which one do you want to trade? 0

You are at the market.  You have $987.85 on hand
Valid commands are:
        buy (to buy cargo)
        sell (to sell cargo)
        available (to see what's available to buy)
        inventory (to show your inventory)
        exit (to exit the market and return to the location)
Enter next command: s

Possible items to trade:
0: 3 units of Gold at $9.05 per unit (total price in market: $27.15)
1: 4 units of Medicine at $25.23 per unit (total price in market: $100.92)
Which one do you want to trade? 0

You are at the market.  You have $1,015.00 on hand
Valid commands are:
        buy (to buy cargo)
        sell (to sell cargo)
        available (to see what's available to buy)
        inventory (to show your inventory)
        exit (to exit the market and return to the location)
Enter next command: s

Possible items to trade:
0: 4 units of Medicine at $25.23 per unit (total price in market: $100.92)
Which one do you want to trade? 0

You are at the market.  You have $1,115.93 on hand
Valid commands are:
        buy (to buy cargo)
        sell (to sell cargo)
        available (to see what's available to buy)
        inventory (to show your inventory)
        exit (to exit the market and return to the location)
Enter next command: e

You are at a Londinium
You have $1,115.93 on hand
Valid commands are:
        travel (to travel to another location)
        market (to enter the market)
        worldmap (to print out the map)
        inventory (to show your inventory)
        quit (to leave the game)
You can abbreviate any command by its first letter
Enter next command: q

You ended the game with $1,115.93
Goodbye!

Congratulations, Space Trader!
Your InterGallactic Thunderbird traveled 5.54 million kilometers.
You still have 972.31 gozorkas of fuel available.
Take the rest of the day off, Space Trader -- you deserve it!

Submission

The good programming practices from HW J1 need to be in this homework as well. 

When you are finished, submit the Universe.java file.

spacer.gif
spacer.gif footer-middle.gif spacer.gif