Java - Fancy Two Dimesional Arrays - java

I am creating a video game were the player can enter and exit rooms. They may also enter rooms within room or sub-rooms. After all of the collision for this I come up with five Rectangle variables/arrays.
static Rectangle exitDoor[] = new Rectangle[1];
static Rectangle subExitDoor[] = new Rectangle[1];
static Rectangle roomDoor[] = new Rectangle[1];
static Rectangle roomLadder[] = new Rectangle[1];
static Rectangle roomInnerLadder[] = new Rectangle[1];
Each room can have multiple of each within. I would like to put all of these arrays within an array that creates two versions of them. What I mean is that if the final two dimesional array is named "room" than room[0][0] and room[1][0] (The second zero being the exitDoor array) would be two different values.
I have tried doing the below, but all it does is do the same thing as the first set of code.
Rectangle[][] roomCat = new Rectangle[][] { exitDoor, subExitDoor, roomDoor, roomLadder, roomInnerLadder };
I am not looking for someone to tell me how to make two dimensional arrays, I can al ready do that. I need someone to tell me how to take them to the next step.
Thanks,
Oak

Well, I didn't understand what you are trying to do with two dimensional arrays. Actually there is nothing special about two dimensional arrays, they are just array of arrays, if you know what I mean.
However if we look back what are you trying to do in the first place. It's not actually very complicated task.
Actually what you're trying to do is a very interesting concept in many areas such as mathematics and art, which is called self-referencing. You can see self-referencing in the paintings of Escher and in the conans of Bach. Take a look at the class below.
class Room {
Room outerRoom;
Room innerRoom;
Room(Room outerRoom, Room innerRoom) {
this.outerRoom = outerRoom;
this.innerRoom = innerRoom;
}
// goes to outerRoom
Room exit() {
return outerRoom;
}
// goes to innerRoom
Room enter() {
return innerRoom;
}
}
It's an implementation of a room in your game. As you mentioned there might be another room inside the room, therefore there might be another room outside the room. So if we want exit the room we go to outerRoom. What handy about this implementation is the outerRoom is a Room too. Therefore it contains inner and outer rooms as well.
You may think this class as a matryoshka doll however what we actually implemented is a basic linked list. You can look it up on the internet, and you can use it while you're making your game however it seems like you're looking for something more.
You want to have many rooms inside a room. What you're looking for is a tree, my friend. Look at the class below:
class Room {
Room outerRoom;
Room[] innerRooms;
// creates a room with n inner rooms
Room (Room outerRoom, int n) {
this.outerRoom = outerRoom;
this.innerRooms = new Room[0];
}
// sets nth room to innerRoom
void addRoom(int n, Room innerRoom) {
innerRooms[n] = innerRoom;
}
// goes to nth room
Room getRoom(int n) {
return innerRooms[n];
}
}
It's another implementation of a room in your game. Instead of having an inner room, we have an array of inner rooms this time. So you can have as many rooms as you want in the room however you can only have one room outside, just like a node of a tree.
So, I recommend you to look up linked lists and trees on the internet to understand the concept of this kind of self-referencing structures.
Also notice that if there isn't any room outside you can make it null, and if you don't want to have any inner rooms you can set the number of inner rooms to 0.
I hope it helps :).

Related

Adding contents of several linked lists to a larger linked list and updating it continually

I am programming a 2D game in Java Swing. I have created several LinkedLists to hold instances of classes Tower, Entitiy and TowerBuildButtons. After I did this I realized that I want to have a superclass to all of these: Selectable. This is because all of these elements should have the capability to be selected and hovered over with the mouse. So I created the superclass Selectable and an additional LinkedList selectables.
The problem I am facing here is: When I add additional objects to the smaller lists (entities, towers, etc...) I also want them to be added to the larger selectables list. I can think of one solution to this. Creating a new add-method and making sure that when new objects are added, they are also added to selectables list. Example:
void addTower(Tower t) {
towers.add(t); //Adding new tower object to the list of towers
selectables.add(t); //Also adding the object to the list of selectables
}
However, I suspect there is a better way of solving this problem. So: How can I make sure that the selectables list is updated when its sublists are? or: How can I make a list of sublists that updates properly when new elements are added to the sublists?
Code for my linked lists:
//LISTS OF GAME OBJECTS
public static LinkedList<Entity> entities = new LinkedList<Entity>();
public static LinkedList<Block> blocks = new LinkedList<Block>();
public static LinkedList<Tower> towers = new LinkedList<Tower>();
public static LinkedList<Projectile> projectiles = new LinkedList<Projectile>();
//List of anything that is a subclass of Selectable(buildBtns, towers, entities)
public static LinkedList<Selectable> selectables = new LinkedList<Selectable>();
//LISTS OF INTERFACE OBJECTS
public static LinkedList<BuildTowerButton> buildBtns = new LinkedList<BuildTowerButton>();
Higher memory imprint
I would suggest you create a Board singleton.
Then adding a Tower, for instance, would be handled by a Board.add(Tower).
This way, you could implement the Board in such a way that adding a Tower registers it both in the towers and selectables collection:
public Board add(Tower tower){
towers.add(tower);
selectables.add(tower);
return this;
}
Lazy evaluation
Another idea which would reduce memory imprint but improve CPU usage would be to simply compute your selectables on demand:
public List<Selectable> getSelectables(){
return new LinkedList<Selectable>().addAll(/*first list of Selectables*/)
.addAll(/*second list of Selectables...*/);
}
Note
I would advocate against usage of public static variables and go for the singleton, so that you are sure that there is exactly one way of adding a Tower to your Board, hence no one can "forget" to update the selectables collection as well.

Understanding the theory, but not able to construct a multi-class project?

So this is my very first mini-javaproject and I have been stuck for days now on the basic structure and the (non existing) relation between anything within my code. I linked the code in my comment below, could not paste it in here for some reason - (Main is empty, so did not copy it.)
So I spent some time getting my head around the basics of Java (as my first programming adventure) and to be honest I felt pretty confident. (On Codewars I completed like 100+ Katas, but of course those are "single-class", so I was not prepared for the "real world.)
It is hard to exactly pinpoint my question, but I will try to give some examples.
1, (Main is empty right now, but anyway) Basically "nothing can be used" in main. Like methods of objects, like room1, or player1, etc.
2, In my Room.java line 21-22 why is the object room1 not visible? Why does Intellij say "Unknown class: RoomArray if I just created that very thing before??
3, I understand that I am supposed to have my variables set to private, which I plan to do later on. Also, I should use setter and getter methods, which I tried to do so with basically everything. But for example in Player.java I have this
Player player1 = new Player(300, 50, "Conan", 75, false);
public Player getPlayer1() {
return player1;
}
and if I try to use the getPlayer1() method in any other class it just simply can not see/access it?
3, And to make me even more confused Room1 class has access to getMyDungeon () method created in the Dungeon class. Why is that so?
(Maybe it has to do with inheritance? The fact that Room1 extends Room which extends Room? But if so, it seems strange because not all classes can have a HAS-A or IS-A relationship with something. An example - if I create all 10 Rooms later on as Room1, Room2, etc. in separate classes, how could I ever create a Room [] array containing them? No matter where I started to do that it will always give me the error "Cannot resolve smybol" for all the Room objects...)
I have spent the past few days reading up on the topic and understand it all, but still when I try to build this project it all falls apart. I realize that an experienced programmer might not even my question because how basic it is, but if anyone can help me to get this whole thing clear in my head, I would appreciate it. (Really not looking for the complete code, but just some direction I should go, or the missing step, etc.)
It seems you to be trying to create an object within the class of that object The correct use is:
public static void main(String[] args){
Player player1 = new Player(300, 50, "Conan", 75, false);
}
or if you want your Room class to have a lot of players
public class Room {
//this object will be create when you do Room room = new Room();
List<Player> players = new ArrayList<>();
public void createPlayer(){
players.add(new Player());
}
//this is a getter
public List<Player> getPlayers() {
return players;
}
}
your Player:
public class Player {
//Fields and Methods
}
and your main:
public static void main(String[] args)
{
Room room =new Room();
room.createPlayer();
for (Player p:room.getPlayers()) {
//p.doSomething
}
}
if you want an object to be created without the need to create an instance from the outside you need to use the static keyword (don't do that unless you know what you are doing)
static Player player1 = new Player(300, 50, "Conan", 75, false);
public static Player getPlayer1() {
return player1;
}

How to Determine If a Collection Is Empty

I have a 3 dimensional ArrayList and I want to determine if it is empty or not. There is an exception called EmptyCollectionException which is not part of java standard library and hence I'm not allowed to use it.
Is there a way to accomplish that using a native java exception or function?
The 3D List is constructed as follow:
public void makeRandomCardListForLearning (Course courseToBeMadeRandom) {
List<List<List<Card>>> course = new ArrayList<List<List<Card>>>();
for(Chapter chptr: courseToBeMadeRandom.getChapterList()) {
List<List<Card>> chapter = new ArrayList<List<Card>>();
course.add(chapter);
for(Deck dck: chptr.getDeckList()) {
List<Card> deck = new LinkedList<Card>();
chapter.add(deck);
for(Card crd: dck.getCardList()) {
if(dck.isTheCardDueToday(crd.getLastDate())) {
deck.add(crd);
}
}
Collections.shuffle(deck);
}
}
}
As I go through course, chapter and deck I create a List for each one. There is only one course, many chapters, many decks and of course many cards which are saved under deck doublyLinkedList if they pass the pre-condition. If no card passes the condition, I have a 3D list which exists but has no cards. And I want to determine that If no card exists in the list, then the user receives an error message.
In fact I only need the cards. But I also need to know in which deck each card resides at the moment. If I just make a list and go through all chapters and decks and put cards in that list based on the condition then I have no clue in which chapter and deck each card resides. That can be solved by maybe adding two attributes to the card class. But that was a mistake as we designed the system and adding them now costs a lot of change in other parts of the program. Each index in course List represents the chapter number and each index in chapter list represents the deck number. I solved the problem that way.
This should do it:
public static boolean isEmpty(List<List<List<Card>>> list3d) {
return list3d.stream().flatMap(llc -> llc.stream()).flatMap(lc -> lc.stream()).count() == 0;
}
It takes into account that the outer lists may contain empty inner lists. It deems the entire 3D list empty if there are no cards in it.
you can do something like this
List<List<List<Card>>> course = new ArrayList<List<List<Card>>>();
// some possible codes
boolean check = course.isEmpty()
// other possible codes
if (check) {
// do something
}
or any arraylist you want to check or any way you want to reach your goal

I need to sort games in an array using title, developer, genre, etc

I am not sure how to do much with arrays yet and can't figure this out. Here is the full assignment.
Write a JAVA program that maintains a list of computer games using an array. Your main program should display the following menu repeatedly.
i. insert game
s. search game
p. print list
q. Quit
Select:
The array stores a list of computer games and each game in the list consists of title(string, key), developer(string), genre(string), year of production(int), and price(float). The list should be maintained in the increasing order of the key(title).
Option i should read a game(title, developer, genre, year, price) and insert the game into the array. Note that the new game should be inserted into the right spot so that the entire array may remain sorted. Sorting entire array again after adding the new game at the end of the array is costly and hence not acceptable. Option s asks for a game title and lists all the games matching with the title entered. Note that two or more games may have the same title. Option p simply lists all the games stored in the array.
We will assume a maximum of 100 games.
And here is what I have so far
package lab12;
import java.util.Scanner;
// create second class to hold methods
class next {
// create "insert game" method
public void insert( ) {
System.out.println("Insert");
}
// create "search game" method
public void search( ) {
System.out.println("Search");
}
// create "print list" method
public void print( ) {
System.out.println("Print");
}
// create method to
}
public class Lab12 {
public static void main(String[] args) {
Scanner in = new Scanner( System.in );
// create string to see what user wishes to do
String choose;
// create instance of other class
next choice = new next();
do {
// see which method user wants to use
System.out.print("Do you want to insert game (i) or search game (s) "
+ "or print list (p) or quit (q)? ");
// create string to see which method to go to
choose = in.nextLine();
// send user to correct method
if ( choose.equals("i") || choose.equals("I"))
choice.insert();
else if ( choose.equals("s") || choose.equals("S") )
choice.search();
else if ( choose.equals("p") || choose.equals("P") )
choice.print();
} while ( choose.equals("i") || choose.equals("s") || choose.equals("p")
|| choose.equals("I") || choose.equals("S") || choose.equals("P"));
}
}
I'm not sure how to sort the games in the array, it says to sort it by key but I don't know how to put in the key with the string. I'm not good with arrays either so I don't know how you can have all of the information linked together.
Thank you for all of your help!
Sincerely,
A stressed out college student.
Like Nimble Fungus stated, the first step is to create a Game class that will be your object representing games in your array.
If you're not concerned about efficiency, the Collections library had a built-in sorting method you can use. If you do need to worry about efficiency (for example, a massive data set) you should look into implementing a more advanced sorting algorithm. Although, I'm fairly certain Collections.sort implements Merge Sort, which should suffice in most situations.
To use Collections.sort on a datastructure containing objects, you must provide a Comparator in the method call:
Collections.sort(array, comparator);
For information on creating and using a comparator object, check out the documentation .
Also, if you plan on only using this comparator once, I might recommend creating an anonymous class, rather than creating a whole new class in your project. Here is the documentation for creating and using anonymous classes.
One last point to mention is that rather than creating a new comparator, you could actually have your Game class implement Comparable which would allow you to define the natural ordering of your Game objects at their creation.
John, create a POJO with all four parameters.
Sort the array or list on each insert using comparator. Use below link to know more .
http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator
Or u can even use sorted map with key as game name .

Keeping track of scores in Java

I'm new to Java and I'm currently writing a program for an assignment that represents a 'sports league' (classes to represent player/club/match/league)
My main problems are occurring in the league class. Here are the relevant variables to give you an idea how I'm storing things:
public class League
{
private String leagueName;
private ArrayList<Club> clubs;
private ArrayList<Match> fixtures;
private ArrayList<String> results2;
private TreeMap<Match, String> results;
private String topTeam;
private String goldenBoot;
}
Currently trying to write a method in the League class which will print a 'league table' - i.e. a list of Clubs sorted by their points tally (held as variable in Club class) and I'm drawing a blank on it.
Further to this, I need to write two methods to find the top scorer (golden boot) and find the top team in the league; again I am drawing a blank. Perhaps I am overcomplicating things?
Would be very grateful for suggestions/sample methods
EDIT:
Ok, so that method I'm trying to write is something beginning with:
public void getLeagueTable() {
for(Club c : clubs) {
c.getTally();
}
}
which would give the tally value for each Club object - but how to sort these results, and how to associate the highest with one Club is what's really troubling.
To print the league table, you are going to need to sort the club array and then loop through each item and print the club name.
To sort the club array try using Collections.sort http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html
.. that is assuming you havent been told to implement your own algorithm
Again, more sorting required to get the top team and top scorer, then you will need to pick the top item from the sorted list.
Hope that helps...
You better use Set rather than ArrayList. And here is a good start for your question :
void printLeagueTable(){
i = 0 ;
while( i != clubs.size() ){
Club club = clubs.get(i);
System.out.println("club: "+i+ "points: " club.points() );
}
}

Categories