Java 如何让一个人在此代码中保留对玩家的引用?
问题:当骨架进入某个位置时,我希望在我的Java 如何让一个人在此代码中保留对玩家的引用?,java,object,game-engine,modeling,Java,Object,Game Engine,Modeling,问题:当骨架进入某个位置时,我希望在我的世界中使用此方法更新所有玩家屏幕对象: /** * Say `text' in the Place `place'. The text will become visible at the * bottom of the text window of any Players currently watching `place'. * * @param place * The place where the string w
世界中使用此方法更新所有玩家屏幕
对象:
/**
* Say `text' in the Place `place'. The text will become visible at the
* bottom of the text window of any Players currently watching `place'.
*
* @param place
* The place where the string will be displayed.
* @param text
* The string to be diplayed.
*/
public void sayAtPlace(Place place, String text) {
synchronized (players) {
Iterator<Player> ls = players.iterator();
while (ls.hasNext()) {
Player p = ls.next();
if (p.currentPlace() == place) {
p.say(text);
}
}
}
}
你明白我想做什么吗?我想要的代码是
System.out.println("player:"+player);
if(player != null && this.name.equals("Skeleton")){
player.say("A terrifying skeleton warrior appears!");
}
但是僵尸的玩家参考并没有实例化。唯一实例化玩家对象的人是同时也是个人的玩家
你能帮我吗?我还在这里发布了个人、玩家和世界职业的完整版本
(人)
(球员)
(世界)如果我能很好地理解你的问题,你需要有两个类,每个类都有一个对另一个的引用。您需要创建一个类(让它成为
Foo
),创建另一个类(让它成为Boo
),并通过构造函数将Foo
的引用传递给它,然后通过setter方法在Foo
类内部设置Boo
的引用
例如:
public static void main(String[] args)
{
Foo f = new Foo();
Boo b = new Boo(f);
f.setBoo(b);
}
class Foo
{
private Boo b;
public Foo()
{
// ...
}
public void setBoo(Boo b)
{
this.b = b;
}
}
class Boo
{
private Foo f;
public Boo(Foo f)
{
this.f = f;
}
}
现在,
Foo
引用了Boo
,Boo
引用了Foo
:)如果我理解你的问题,你想有两个类,每个类都有一个引用。您需要创建一个类(让它成为Foo
),创建另一个类(让它成为Boo
),并通过构造函数将Foo
的引用传递给它,然后通过setter方法在Foo
类内部设置Boo
的引用
例如:
public static void main(String[] args)
{
Foo f = new Foo();
Boo b = new Boo(f);
f.setBoo(b);
}
class Foo
{
private Boo b;
public Foo()
{
// ...
}
public void setBoo(Boo b)
{
this.b = b;
}
}
class Boo
{
private Foo f;
public Boo(Foo f)
{
this.f = f;
}
}
现在,
Foo
引用了Boo
,而Boo
引用了Foo
:)首先,您应该在构造函数中实例化此人的成员“player”
this.player = new Player(world, this);
然后,将代码从
public void goTo(String place) {
goTo(world.getPlace(place), null);
}
到
首先,您应该在构造函数中实例化此人的成员“player”
this.player = new Player(world, this);
然后,将代码从
public void goTo(String place) {
goTo(world.getPlace(place), null);
}
到
你的Person构造函数中从未使用过this.player,这正常吗?请你缩短程序,使其包含的内容足以显示问题?@Adel Boutros你说得对,这就是问题所在。如果我能将玩家实例化为Person Constructor,那么问题就解决了。但是当我成为一个人的时候,我没有球员。我需要以某种方式耦合对象。你的
Person
类有一个Player
引用,反之亦然,如果需要的话,这永远不是一个好迹象。我认为您需要尝试清理您的类层次结构。我正在测试它,现在它可以工作了。感谢您的帮助。this.player从未在您的Person构造函数中使用过,这正常吗?请您缩短程序,使其包含的内容足以显示问题?@Adel Boutros您是对的,这就是问题所在。如果我能将玩家实例化为Person Constructor,那么问题就解决了。但是当我成为一个人的时候,我没有球员。我需要以某种方式耦合对象。你的Person
类有一个Player
引用,反之亦然,如果需要的话,这永远不是一个好迹象。我认为您需要尝试清理您的类层次结构。我正在测试它,现在它可以工作了。谢谢你的帮助。如果你阅读了关于这个问题的评论,他说在创建类Boo的实例时,还不知道类Foo的实例。因此,他无法通过该引用constructor@AdelBoutros然后他可以做相反的事情。如果你阅读了关于这个问题的评论,他说在创建Boo类的实例时,Foo类的实例是未知的。因此,他无法通过该引用constructor@AdelBoutros然后他可以做相反的事情。其中一个应该在创建另一个之前存在。