I'm very new to Java and am not sure if I'm even allowed to ask questions of this nature here but I'll give it a shot. I want/need practice programming Java so I've decided on a rather large project that should be within my capabilities I've started building it and have created a player object with some properties like level,name,xp,health and items. The items are and array of 5 object objects (bear with me XD) now I'd like to know if I should create the rooms as objects as well or as seperate classes or functions?
The rooms will be only rooms in an abstract sense the game is fully text-based they will need to contain puzzles and objects a user can pick up or examine as well as enemies and such the narrative will also be contained in each one. The player will be able to "pick up" items in the room and add them to their inventory. As well as participate in textual comabt with enemies like : you hit monster for 2 damage, monster hits back for 3 etc.
Remember that this isn't going to be pretty it's for practice and I need to do it within Java.
Thanks in advance.
Your problem is related to the OOP concepts not to being a beginner in java, you should know more about OOP to think correctly before starting coding to put the correct OOP design for your program. since you are building this program in java you can start here.
For what I've understand from you question, you may want to have a Room Class, Containing the Room Properties and Functions.
From a high level, a good idea would be having a "Room" class, this would contain the Room Title, Description and any other room specific information (such as terrain type etc).
You could then create a multidimensional array of Room objects. One dimension being your X coordinate while the other your Y coordinate.
This way to "move" around all you need to do is track your location and either increment/decrement your X or Y based on the direction you moved.
You could extend it further doing something like generating a map of your surroundings as well. Each terrain type could be displayed as a different symbol (# for forest, ~ for water etc). It would be a simple approach to add something like this because all you need to do is get your top right/bottom left coordinate and loop through those coordinates building your map.
Related
I'm trying to store a list of different Enemies. Each Enemy has an origin and can only spawn in its Location of origin. Each enemy also has a difficulty and should be stored with enemies of the same difficulty.
I imagined it as a static 3D array of Enemies like this:
Enemy[mountain][2][5] = new Enemy("troll")
Where the fields are (from left to right) Location, difficulty, index.
Each location the player enters will populate an ArrayList of Enemies from this static array.
Is there a more efficient data structure to use in this scenario?
(This list will be hard-coded and should not be altered during the course of the program)
edit-
I was hoping to optimize the access time. This game will generate a number of locations, each one needing to randomly draw Enemies from the list based on their origin and difficulty.
As per request, I will put some more thought into the use case of this program. Once I have a proper solution I will update. (Thanks)
It is conceptually wise not a good idea.
You really do not worry about performance at this point. You worry about creating a useful, helpful object model that allows you to write elegant, easy-to-read and easy-to-enhance code.
Using a 3D-array achieves none of these goals.
In other words: you step back; and think hard about the "use cases" that need to access your Enemy objects. And coming from there, you decide if you should go with different Maps for example; or different Sets, ... instead of using a 3D as central "storage point".
Edit, given your comment: there are two sides here:
Arrays are very inflexible in Java. You can't change their size dynamically. And beyond that, they are really "ugly" to use: this going through "3 dimensions" might be convenient for a certain "ascess path"; but it could make other things very hard (like when searching for a certain enemy, then you have to do this 3-dim iteration stuff ... as said: ugly)
One should try to make designs that are "open" for changes that have a high rate of "taking place". Example: you have a fixed number of enemies today; but assuming your "game" works out for you; you will sooner or later (rather sooner) want to enhance it; for example by allowing dynamic add/removal of enemies. Then a lot of the code you wrote using the 3-D array ... would become a real obstacle.
Beyond that: yes, in a "game world", there should be one component that is responsible for keeping track of all elements in the game. But: how this component internally organizes things is more of an implementation detail. You should focus on putting "helpful" methods on that GameWorld first; or as I put it before: understand the ways how your code will need to access/iterate/search enemies to perform the game itself. And then you look into data structures that support these "use cases".
Finally: assuming that this is a learning exercise - you can still start with a 3d array. It will teach you a lot; I am merely pointing out: you would not do that in a more "real world" application; and if you go for this option, you will soon be confronted with certain limitations/obstacles; just by the nature of your solution.
What comes to mind for me is a map. The location is the key and the value would be a List of objects that represents the enemy and its location - let's call it an EnemyLocation object that contains an Enemy and its location (or you could change Enemy to contain its location which seems like a good idea, but I don't know your code). So, when a player enters the "mountain" region, you do something like enemies.get("mountain") and you get back a List of Enemy objects (or EnemyLocation objects)
This is about an open world game in java where millions of units (special ships) are going to move from one planet to another.
I want to make any ship customizable by using and compounding it out of basic modules, the problem is I don't know how to represent all that information in an efficient way, but what I think is:
use an array of objects (one obj per ship) - but that doesn't seem to work.
make a few predefined types of ships, and represent the number of ships in a fleet with an int, but that would mean throwing away the whole idea of customizing the ships, uhm.
How could I resolve this?
It might be worth reading up on some design patterns, particularly the Flyweight Pattern. Some quick ideas off the top of my head would be to have one instance of each "base" ship and one instance of each of the parts that can be added. Then you can access these shared instances in each other ship. Things like ammo and health can be unique to each ship as they are simple numbers and won't take up nearly as much memory. It may take some thinking but I feel Flyweight is your best starting point. Good luck!
I'm writing a 2d Top-down RPG using the LWJGL alongside with Java 1.6. By now, I have the rendering and input methods working fine and just started to program the game's logic.
So I have a class called World, which holds an ArrayList of Entities. I want to implement simple collision in the game (using intersecting squares), which should be no problem. The only problem I now have is how to access single cells of my List without having to iterate all over it. I have only been able to come up with collision methods which are executed inside each Entity and iterate over all of the entities in my World. That is not fast at all, but I really don't know what to do in order to make it faster.
My game is tile based, but the movement is not tile-to-tile, one can walk smaller portions, which avoids me to simply use a two-dimensional array...
Is there a standard way to handle entities and their collisions? (or maybe a way to handle collision between entities which are located inside an ArrayList?)
The standard way to handle colliding entities is by space partitioning. Your world is a 2 dimensional plane made of discrete points.
Each piece can be located on one of the points. The amount of the points determines the resolution of the plane- the more points, the better visual effect, the more calculations you have to perform. This is the trade off.
You can maintain a map between the location of an entity and the entity itself, where the location is represented by an object that overrides equals and getHashCode. The location object contains two members- the X and Y coordinates.
Note- you have to override in a proper and efficient manner.
So you you can access each entity very quickly if you know its coordinate, reshuffling is simply removing an entity and adding it with new coordinates (this can be optimized for locality) and collision detection is trivial- just check whether the same location is occupied by a certain entity.
I would also refer you to this question on SO.
I'm building a RPG dungeon game in Java and I'm stuck on creating a data structure.
I have a lot of Thing objects that I can copy to populate a dungeon with. For instance, there is a bread Thing object, and a sword Thing object, a chain mail Thing object, and monster Thing(s), etc. I want to store them in a central Library and then be able to retrieve an object using certain queries. I want to store them using the following fields:
int minLevel
int maxLevel
double probability
int[] types
So a rusty sword would have a minLevel of 1, a maxLevel of 3, a probability of rarity(3%),and [type.SWORD,type.WEAPON,type.ITEM,TYPE.EQUIP]. A better sword would have minLevel 2, maxLevel 10, rarity (1%).
Then I want to retrieve a random type.SWORD from the library and say I'm at level 3. I should get a rusty sword more often than the better sword based on their probabilities. If I retrieved a type.SWORD from the library requesting level 10, I would only get back the better sword.
I hope this makes sense.
EDIT
At the initialization stage, all the basic objects will be created. Things like the available weapons, armor, foods, potions, wands, all the basic possible Things that have a unique graphic tile in the game. Then when I want to place an object somewhere, I just make a copy of one of the available Things, adjust it's stats a little, and plunk it down in the world. The actual items are all subclass of the root Thing class, such as class Creature,Item,Equip(extends Item),Weapon(extends Equip),Armor(extends Equip),Food(extends Item), etc. But I want to tag them different in the Library database, I want to use extra tags, such as type.RARE, type.ARTIFACT, type.CURSED, so I want extra tags besides the class.
The game use LIBGDX to be available on Android and as an Applet. I use the free Rltile set, which has thousands of good tiles. I will use Pubnub or Google App Engine to provide multiplayer support.
i can think of three answers:
write your own Library that stores these things in Maps with custom methods.
so you might have a Map<Type,List<Object>> that stores lists of things by type
and then a method that takes a type, retrieves the list from the map, and selects
something by probability (that's easy to do - you just some up the probabilities,
generate a random number between 0 and the sum, and then walk through the list,
subtracting the item's probability from your random value until it's negative - you
return the item that made it negative[*]). you can also filter the list first by
level, for example.
if you have a real mix of different things, and don't want to base this on types,
then another option (slower, but more flexible) is to place everything in a list
and then filter by your needs. a nice way to do that is with guava - see
Iterables.filter and Predicate at https://code.google.com/p/guava-libraries/.
you could provide an interface that takes a predicate and returns a random
selection from whatever is left after filtering. predicates are easy to construct
"inline" with anonymous classes - see examples at
https://code.google.com/p/guava-libraries/wiki/FunctionalExplained#Functions_and_Predicates
stick all this in a database. maybe i am too enterprisey, and games people would
never do this, but it seems to me that a small, embedded database like sqlite or
H2 would be perfect for this. you can then select things with SQL queries (this
is already a long answer so i won't give more details here).
change your design. what you describe is not very OO. instead of having types,
your Things could implement interfaces. so the Weapon interface would have a
getMinLevel() method, for example. and then, with a design like this, use a
database with ORM (hibernate).
what you're doing is kind of ambitious and i suspect is more about learning than anything else (no criticism intended - this is how i learn stuff, by making things, so just assuming you are like me). so choose whichever you feel most comfortable with.
[*] this assumes that you always want to return something. if the probabilities are normalized and you want to be able to return nothing, select the initial value from 0-1 (or 0-100 if using percentages). and, if nothing turns the value negative when you run through the list, return nothing.
The easiest approach is to put all your objects in a single large arraylist, and use repeated sampling to select an object.
The procedure to select a random item is very simple:
Select a random number from 0 up to the size of the ArrayList
Get the object at that index from the library
If the object fails to meet any criteria you specify (e.g. "is a of type.SWORD or type.MACE?") go back to start
If the object is outside the minimum or maximum level, go back to start
If the object has a rarity of less than 100%, create a random number from 0-100%. If the random number exceeds the object's rarity, loop back to start. Most objects should have a rarity of say 10-100%, if you want extremely common objects then you can add them multiple times to the library.
This procedure will produce an object that meets the criteria sooner or later (if it exists) and will do so according to the rarity percentage.
The one slight trickness is that it will loop infinitely if no such object exists. Suppose there is no weapon in the library at level 17 for example? To get around this, I would propose widening the minLevel and maxLevel after every 100 tries to ensure that eventually one is found. Ensure you always have a level 1 object of each type available.
For safety, you might also want a bailout after say 100,000 tries (but remember to throw an exception - this is a problem if you are asking for things that don't exist in the library!).
P.S. I implemented a similar library system in a roguelike game called Tyrant that I created many years ago. Source is here if you are interersted:
https://github.com/mikera/tyrant/blob/master/src/main/java/mikera/engine/Lib.java
I want to implement a reinforcement learning connect four agent.
I am unsure how to do so and how it should look. I am familiar with the theoretical aspects of reinforcement learning but don't know how they should be implemented.
How should it be done?
Should I use TD(lambda) or Q-learning, and how do MinMax trees come in to this?
How does my Q and V functions work (Quality of action and Value of state). How do I score those things? What is my base policy which I improve, and what is my model?
Another thing is how should I save the states or statesXactions (depending on the learning algorithm). Should I use neural networks or not? And if yes, how?
I am using JAVA.
Thanks.
This might be a more difficult problem than you think, and here is why:
The action space for the game is the choice of column to drop a piece into. The state space for the game is an MxN grid. Each column contains up to M pieces distributed among the 2 players.This means there are (2M+1-1)N states. For a standard 6x7 board, this comes out to about 1015. It follows that you cannot apply reinforement learning to the problem directly. The state value function is not smooth, so naĆve function approximation would not work.
But not all is lost. For one thing, you could simplify the problem by separating the action space. If you consider the value of each column separately, based on the two columns next to it, you reduce N to 3 and the state space size to 106. Now, this is very manageable. You can create an array to represent this value function and update it using a simple RL algorithm, such as SARSA.
Note, that the payoff for the game is very delayed, so you might want to use eligibility traces to accelerate learning.