Java Forum / First Aid / January 2005
objectA gives objectB to objectC
thufir - 27 Jan 2005 08:43 GMT given that the class Sword is in an entirely different package, Weapons.jar, for which the source code is unavailable, can one monster give an instance of Sword to a second monster instance? something like:
{ //put this in TestDriveMOnsters Sword excalibur = new Sword(); Monster barney = new Monster(); Monster fred = new Monster(); //barney gets excalibur, but how? //barney gives excalibur to fred, but how? }//end example
How does barney even get excalibur?
//////////////code////////////// package atreides.monsters;
public class Monster{
boolean isDaemon = false; java.util.Timer melee = new java.util.Timer(isDaemon);
public Monster(){}//Monster
public void setScheduleMelee(long period){ System.out.println("..setScheduleMelee"); period = 4000; java.util.TimerTask dummyTask = new MonsterTask(); java.util.Date nowDate = new java.util.Date(); melee.scheduleAtFixedRate(dummyTask,period,period); }//setScheduleMelee
public static void main (String args[]) { System.out.println("main.."); }//main }//Monster
////////////////////////////code/////////////////// package atreides.monsters;
import java.util.*;
public class TestDriveMonsters{
private static List<Monster> list = new ArrayList<Monster>();
public TestDriveMonsters(){ System.out.println("TestDriveMonsters.."); }//TestDriveMonsters
public static void makeMonsters(){ System.out.println("..makeMonsters"); for (int i=0; i<5; i++){ list.add(new Monster()); }//for }//makeMonsters
public static void setTimer(){ System.out.println("..addTimer"); for (Monster monster:list){ }//for }//setTimer
public static void main (String args[]) { System.out.println("..main"); makeMonsters(); setTimer(); }//main }//TestDriveMonsters
//////////////////////code///////////////
package atreides.monsters;
public class MonsterTask extends java.util.TimerTask{
public MonsterTask(){}//MonsterTask
public boolean cancel(){ return false; }//cancel
public void run(){ System.out.println("..run"); }//run
public long scheduledExecutionTime(){ return 0; }//scheduledExecutionTime
public static void main (String args[]) { System.out.println("main.."); }//main }//MonsterTask
thanks,
Thufir Hawat
hilz - 27 Jan 2005 09:27 GMT > given that the class Sword is in an entirely different package, > Weapons.jar, for which the source code is unavailable, can one monster > give an instance of Sword to a second monster instance? Sure, why not. Just let him put enough stamps on the package.
> How does barney even get excalibur? By Fedex.
> thanks, > > Thufir Hawat You're welcome. If you have any more homeworks, please do not hesitate to post here, specially when you have shown so much interest and effort in solving them by yourself as you did in this one. Best of luck. hilz.
thufir - 27 Jan 2005 10:32 GMT [..]
> You're welcome. If you have any more homeworks, [..]
What led you to that conclusion?
-- Thufir Hawat
Stefan Schulz - 27 Jan 2005 11:01 GMT > [..] >> You're welcome. If you have any more homeworks, > [..] > > What led you to that conclusion? Well, you _do_ ask a lot of questions that normally (sorry) an novice with little to no grasp on the language would ask. I suggest you do some easier, smaller projects before you tackle what looks like a pretty complicated game. Get a "feel" for the language, get fluent in it. (Sorry to say so, but you are far from it right now).
 Signature In pioneer days they used oxen for heavy pulling, and when one ox couldn't budge a log, they didn't try to grow a larger ox. We shouldn't be trying for bigger computers, but for more systems of computers. --- Rear Admiral Grace Murray Hopper
thufir - 27 Jan 2005 13:30 GMT [..]
> Well, you _do_ ask a lot of questions that normally (sorry) an novice with > little to no grasp on the language would ask. I suggest you do some > easier, smaller projects before you tackle what looks like a pretty > complicated game. Get a "feel" for the language, get fluent in it. (Sorry > to say so, but you are far from it right now). [..]
Most every day I make some progress. What better way to get fluent than to tackle something beyond my reach? I doubt I'll finish the game, it's more an exercise.
I've the monsters periodically executing MonsterTask.run(), next I'll have monster 1 kill monster 2 :)
-- Thufir Hawat
Stefan Schulz - 27 Jan 2005 17:30 GMT > Most every day I make some progress. What better way to get fluent > than to tackle something beyond my reach? I doubt I'll finish the > game, it's more an exercise. Well, i just doubt the value of an exercise done by the newsgroup. ;)
Honestly, you won't always have a handy bunch of programmers ready to help you out. Especially if your game progresses to be more complex then 3-4 classes, you'll need to be able to condense problems down to 1-2 classes.
Please don't take this as a personal attack, but you'll need some more experience with tackling problems yourself. Get a book. Read it. Take a good long walk in the JavaDocs, and jam yourself behind your computer for a couple of hours if you have a problem. Post only if you can't find the answer yourself. You'll learn things you never thought you might have to know.
> I've the monsters periodically executing MonsterTask.run(), next I'll > have monster 1 kill monster 2 :) Hmm... how about a bet? If you manage to make that happen (and so that monster 2 won't come back from the dead, and monster 1 gets notified when it tries to kill the dead monster again), i'll revise my views. :)
 Signature In pioneer days they used oxen for heavy pulling, and when one ox couldn't budge a log, they didn't try to grow a larger ox. We shouldn't be trying for bigger computers, but for more systems of computers. --- Rear Admiral Grace Murray Hopper
hilz - 27 Jan 2005 19:23 GMT > [..] > > You're welcome. If you have any more homeworks, [quoted text clipped - 4 lines] > -- > Thufir Hawat Ok. I appologise. Reading your other posts, I can now tell it is not really a homework. But what really made me think that way was: "for which the source code is unavailable".
But as Stefan said, you need to learn the basics before diving into the code. Learning by trial and error is ok, but you need to get a basic level of understanding of object oriented programming first. Consider reading a book, or reading some literature on the web. You can find most of what you need to get started at the java.sun.com website.
Good luck. hilz
thufir - 29 Jan 2005 02:01 GMT [..]
> Reading your other posts, I can now tell it is not really a homework. > But what really made me think that way was: "for which the source code is > unavailable". Ah, I see why you thought it was homework. That was a poor way of asking a simple question on my part.
> But as Stefan said, you need to learn the basics before diving into the > code. Learning by trial and error is ok, but you need to get a basic level [quoted text clipped - 4 lines] > Good luck. > hilz Thanks,
Thufir Hawat
Bjorn Abelli - 27 Jan 2005 09:56 GMT "thufir" wrote...
> given that the class Sword is in an entirely different > package, Weapons.jar, for which the source code is > unavailable, Don't confuse "packages" with "jars". These are two different concepts.
Packages are a "logical" classification of classes, while jars are a "physical" division.
A jar can contain classes from several packages, and there can exist classes from the same package in many jars.
You include the jars in your classpath when compiling and executing, so the JVM can find the classes inside them.
You "import" the packages in you source code, just as you do with "java.util.*", etc...
Say that the full name of Sword really is atreides.weapons.Sword, then you have to
import atreides.weapons.Sword;
or
import atreides.weapons.*;
where you intend to reference to Swords.
> can one monster give an instance of Sword to a > second monster instance? Absolutely.
You could add these lines somewhere in Monster
public class Monster {
private Sword = null;
public void achieveSword (Sword s) { sword = s; }
public Sword returnSword () { Sword s = sword; sword = null; return s; }
public void giveAwaySword(Monster m) { m.achieveSword( this.returnSword() ); } }
> something like: > [quoted text clipped - 3 lines] > Monster fred = new Monster(); > //barney gets excalibur, but how? barney.achieveSword(excalibur);
> //barney gives excalibur to fred, but how? barney.giveAwaySword(fred);
> }//end example Suggestion:
Read up on OO Analysis and Design, the parts that describes responsibilities of objects and classes, sending messages, delegation, etc.
To visualize such events you can also look into how you can use sequence diagrams in UML.
// Bjorn A
thufir - 27 Jan 2005 10:51 GMT > "thufir" wrote... > > given that the class Sword is in an entirely different > > package, Weapons.jar, for which the source code is > > unavailable, > > Don't confuse "packages" with "jars". These are two different concepts. You're right, I meant that the weapons would be in Weapons.jar
[..]
> You could add these lines somewhere in Monster > [quoted text clipped - 16 lines] > } > } [..]
Sorry, I mis-stated my question. Can this be done from *outside* the Monster class? For example, assume that Monster is final and is in package atreides.monsters, for which the .class file(s) are in Monster.jar, and the Monster source code can't be edited.
>From TestDriveMonsters I don't see how a atreides.weapons.Sword instance could be given to a Monster instance (and then to a different Monster instance).
I hope that clarifies what my question is, sorry my initial question wasn't clear enough. I ask this because there might be 500 different "things" a Monster might be "composed" of, none of which can really be anticipated in advance.
Perhaps if Sword implemented interface Givable (or such) that'd eliminate 500 different methods to pick up 500 different objects? I think so...don't know why I didn't think of that before posting.
If an interface were to enable a Monster instance to "get" an object, which is unknown in advance, that's what I'll do. However, is there more than one way to skin this cat, parenthetically speaking? thanks,
Thufir Hawat
Stefan Schulz - 27 Jan 2005 11:05 GMT > I hope that clarifies what my question is, sorry my initial question > wasn't clear enough. I ask this because there might be 500 different > "things" a Monster might be "composed" of, none of which can really be > anticipated in advance. In that case, you should introduce some subclasses of Monster that are generic "kinds" of monster which share common characteristics. For example, you could create a "Humanoid" class, which extends monster, and includes such things as being able to get, wield, and otherwise use items.
> Perhaps if Sword implemented interface Givable (or such) that'd > eliminate 500 different methods to pick up 500 different objects? I > think so...don't know why I didn't think of that before posting. Yes. You could also implement a "take(Item)" method, that enables the monster to take any kind of Item (not just Swords) if it wants, or something similar. This is what OO is really about!
> If an interface were to enable a Monster instance to "get" an object, > which is unknown in advance, that's what I'll do. However, is there > more than one way to skin this cat, parenthetically speaking? > thanks, Of course, there is. For example, either introduce a Takeable interface, that objects that can be taken implement, or introduce an (abstract) Item class, which includes a isTakeable(Monster) method... or a dozen other variations on these themes.
 Signature In pioneer days they used oxen for heavy pulling, and when one ox couldn't budge a log, they didn't try to grow a larger ox. We shouldn't be trying for bigger computers, but for more systems of computers. --- Rear Admiral Grace Murray Hopper
Bjorn Abelli - 27 Jan 2005 11:11 GMT "thufir" wrote...
> [..] > > Sorry, I mis-stated my question. Can this be done from *outside* the > Monster class? For example, assume that Monster is final and is in > package atreides.monsters, for which the .class file(s) are in > Monster.jar, and the Monster source code can't be edited. Do you mean that *both* Monster and Sword are classes that you can't change the source codes for?
In that case you really mislead me, as you provided a sample code of Monster...
To help you further, you should at least provide the interfaces of Sword and Monster, to see what could be done.
>>From TestDriveMonsters I don't see how a atreides.weapons.Sword > instance could be given to a Monster instance (and then to a different [quoted text clipped - 4 lines] > "things" a Monster might be "composed" of, none of which can really be > anticipated in advance. So Monster *alreday* has ways to receive things? And to give them back?
> Perhaps if Sword implemented interface Givable (or such) that'd > eliminate 500 different methods to pick up 500 different objects? I [quoted text clipped - 4 lines] > more than one way to skin this cat, parenthetically speaking? > thanks, I see three ways to skin this cat... ;-)
In order of (my) preference:
1. a Monster has methods to receive and return things.
2. a Sword (or Giveable) has methods to store an owner (such as a Monster)
3. you implement a third "relationship class", which tells which artefact is owned by who.
In many design patterns 1 and 2 are used together, and 3 is very seldom used.
Which one that is best suited is depending on what is already implemented, as it seems your access to the source code seem a bit restricted... ;-)
// Bjorn A
thufir - 27 Jan 2005 11:30 GMT Heh, the access to the source was a (poor) device to ask the question.
Here's what I now have, what do you think of using a List of MonsterItems (an interface)?
package atreides.monsters;
public class Monster{
boolean isDaemon = false; java.util.Timer melee = new java.util.Timer(isDaemon);
private static java.util.List<MonsterItem> list = new java.util.ArrayList<MonsterItem>();
public Monster(){}//Monster
public void setScheduleMelee(long period){ System.out.println("..setScheduleMelee"); period = 4000; java.util.TimerTask dummyTask = new MonsterTask(); java.util.Date nowDate = new java.util.Date(); melee.scheduleAtFixedRate(dummyTask,period,period); }//setScheduleMelee
public static void main (String args[]) { System.out.println("main.."); }//main }//Monster package atreides.monsters;
public interface MonsterItem{
public void give();
}//MonsterItem package atreides.monsters;
public class MonsterTask extends java.util.TimerTask{
public MonsterTask(){}//MonsterTask
public boolean cancel(){ return false; }//cancel
public void run(){ System.out.println("..run"); }//run
public long scheduledExecutionTime(){ return 0; }//scheduledExecutionTime
public static void main (String args[]) { System.out.println("main.."); }//main }//MonsterTask package atreides.monsters;
public class Sword implements MonsterItem{
Sword(){}
public void give(){ System.out.println("..give"); }//give
}//Sword package atreides.monsters;
import java.util.*;
public class TestDriveMonsters{
private static List<Monster> list = new ArrayList<Monster>();
public TestDriveMonsters(){ System.out.println("TestDriveMonsters.."); }//TestDriveMonsters
public static void makeMonsters(){ System.out.println("..makeMonsters"); for (int i=0; i<5; i++){ list.add(new Monster()); }//for }//makeMonsters
public static void setTimer(){ System.out.println("..addTimer"); for (Monster monster:list){ }//for }//setTimer
public static void main (String args[]) { System.out.println("..main"); makeMonsters(); setTimer(); }//main }//TestDriveMonsters
elrond_III - 27 Jan 2005 16:00 GMT With interface it is often meant that you should list all your method signitures! method signature: the mathod name, its arguments, and the return type, usually in the following form: +toStringCopy(str1:String,str2:String):String
This is too called interface because with it you can see the way how you can "communicate" with an object (means which public methods you can call...).
however it is enougth if you write your public methods:
Mean something like: class B { B() public void m1() public void m2(name:String) //bla bla bla }
PS.: If you don't allready know: In Java a interface is a class with just abstract methods, it is used to force classes to implement a specific set of methods. Because then you know a class has them, you can call this class with the type and functions of the interface:
interface A{ abstract public void a(); abstract public int b(); }
class C implements A {
}
class D { public static void main() { C c = new C(); E.handleA(c); <--- i give E a object of type C } }
class E { public static void handleA(A temp) { <-- but E just can handle type A temp.a(); thats not an problem, since temp.b(); C implements A... } }
 Signature -------------------------------------------------------------- Elrond_III -==: Hack the World :==- g:R->R; [a,b] in D(g) and g[a,b] in [a,b] and for all x1,x2 in [a,b]
|g(x1)-g(x2)|<=L*|x1-x2| with L <= 1 then one s in [a,b] exist with s=g(s) -"Banachscher Fixpunktsatz"
thufir - 29 Jan 2005 01:59 GMT [..]
> PS.: > If you don't allready know: > In Java a interface is a class with just abstract methods, it is used to > force classes to implement a specific set of methods. Because then you > know a class has them, you can call this class with the type and > functions of the interface: [..]
What I've got is: "public class Sword implements weapon{" so that in class Monster there's a "List<Weapon> weapons = new List<Weapon>;" which gives some flexability. Then a Sword instance can be changed by iterating through the list and calling methods on an element. I'm not sure if this is a common, or even "good", technique, though. -- Thufir Hawat
Paul - 29 Jan 2005 05:18 GMT > What I've got is: "public class Sword implements weapon{" so that in > class Monster there's a "List<Weapon> weapons = new List<Weapon>;" [quoted text clipped - 3 lines] > -- > Thufir Hawat It is good programming practice, in my experience, to use the abstraction of a class if that is all you need. It is related to never downcasting from the abstract type to the actual type to get something done. It is better for example to use a java.util.List instead of a Vector, ArrayList, LinkedList, or other implementation so you can alter performance in the list initialization and not have to alter the many places in your code you pass that instance. If all you are using are List's things (or Weapon's in your case) then treat a Sword and whatever other Weapon implementations you have as Weapons in the list, which you will probably instantiate like: List<Weapon> weapons = new ArrayList<Weapon>(); If you find yourself needing a part of Sword that is not in Weapon from an object in that list, consider whether it should be known to Weapon and therefore to all implementing classes of Weapon, or just to the specific implementation of Sword. I hope I wasn't too confusing, --Paul
thufir - 29 Jan 2005 09:41 GMT [..]
> You could add these lines somewhere in Monster > [quoted text clipped - 16 lines] > } > } [..]
> To visualize such events you can also look into how you can use sequence
> diagrams in UML. [..]
I need to step away from the code because I go in a chicken-or-egg circle.
It must be possible to view a Monster's MonsterItems (an "inventory" of sorts). It must be possible to change the owner for a MonsterItem from one Monster to another Monster (ignoring "dropping a sword to the ground" for simplicity).
some pseudo-UML:
<<MonsterItem>> excalibur:Sword
<<MonsterItem>> aToothpick:Sword
Barney:Monster -------------- +getMonsterItem(Monster) +giveMonsterItem(MonsterItem,Monster)
Fred:Monster -------------- +getMonsterItem(Monster) +giveMonsterItem(MonsterItem,Monster)
There's an aggregation of many MonsterItems in a Monster, but it's hard to type "open diamond from Monster to MonsterItem" with real diamond shapes ;)
It must also be possible to print "Barney attacks Fred with excalibur for 3 points of damage," which is the litmus test. What's needed to add that
functionality to this model, please? Thanks,
Thufir Hawat who has complete access to the source ;)
thufir - 29 Jan 2005 10:38 GMT [..]
> You could add these lines somewhere in Monster > [quoted text clipped - 16 lines] > } > } [..]
> To visualize such events you can also look into how you can use sequence
> diagrams in UML. [..]
I need to step away from the code because I go in a chicken-or-egg circle.
It must be possible to view a Monster's MonsterItems (an "inventory" of sorts). It must be possible to change the owner for a MonsterItem from one Monster to another Monster (ignoring "dropping a sword to the ground" for simplicity).
some pseudo-UML:
<<MonsterItem>> excalibur:Sword --------------- +printDamage
<<MonsterItem>> aToothpick:Sword ----------------- +printDamage
Barney:Monster -------------- +getMonsterItem(Monster) +giveMonsterItem(MonsterItem,Monster) +printDamageDone +printDamageReceived
Fred:Monster -------------- +getMonsterItem(Monster) +giveMonsterItem(MonsterItem,Monster) +printDamageDone +printDamageReceived
There's an aggregation of many MonsterItems in a Monster, but it's hard to type "open diamond from Monster to MonsterItem" with real diamond shapes ;)
fred.PrintDamageDone should print "Fred uses excalibur" excalibur.printDamage should print "excalibur delivers 4 points of damage" barney.printDamageRecived should print "barney takes 4 points of damage"
However, this model seems deficient in that I don't see how to send messages between the three different objects to effect those print statements.
Thanks,
Thufir Hawat
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|