从另一个类方法调用对象数组的特定成员

时间:2013-06-04 15:23:42

标签: java arrays list methods

我现在正在研究项目的AI部分。我正在从我的AI类中调用一个方法,该方法用于计算我绘制的角斗士对象需要实际结束的位置。我将包含我想要放置的所有对象的List传递给该方法。来自AI类的先前方法确定了他们希望彼此之间的距离,并且我将其存储为角斗士[0..1..2..etc] .movementGoal。

虽然这个项目不是实时的,但我最终还是想“逐步”通过它,我确实希望同时进行移动。这意味着我遍历列表的标准方法将不起作用,因为我需要有关其他角斗士的运动决策的信息,以便在这些决定相互作用时找出任何一个角斗士的实际动作。

当我在课外时,我如何才能访问另一个特定的角斗士变量?

编辑:

我想我可以迭代并测试变量gladiatorNumber是否正确,然后当它拉出那个信息?这将是非常全面的,但我能想到的全部。

EDIT2:

根据要求,一些代码。我在Ai课程中的方法如下:

public void moveAI(List<Gladiator> gladiators) {

我的角斗士的定义如下:

public class Gladiator {

Gladiator类作为数组创建,然后添加到单独的主类中的列表中。我真的不想包含比这更多的代码,因为它有很多。基本上它归结为我如何从AI类调用gladiator [0],即使我在主类中创建了所述对象,并​​且只在AI类中以列表形式使用它们。假设角斗士中的所有变量都是公开的。我得到的错误是找不到指代角斗士[0 ... 1 ... 2 ......等]的符号。

1 个答案:

答案 0 :(得分:1)

我认为你的问题归结为想要将角斗士阵列传递给另一个班级。这应该相当容易。如果你的主类有这两个定义(注意你只需要一个,我推荐列表,因为它更通用,阵列有固定长度)。

你想要这样的东西:

public class Main {
// ....stuff
// This is the main class that keeps the list of gladiators
private List<Gladiator> gladiatorsList;
private Gladiator[] gladiatorsArray;
private MovementAI movementAI;

public Main() {
    // You initialize gladiatorsList and gladiatorsArray as before
    // gladiatorsList = ...
    // gladiatorsArrray = ...
    // Now you want to pass this list/array to another class (the AI), you
    // can do this in the constructor of that class like so:
    movementAI = new MovementAI(gladiatorsList);
}

// ...stuff as before

}

AI

public class MovementAI {

private List<Gladiator> gladiators;

// Giving the class the list-reference, this list will be the same as the
// list in main, when main-list changes so does this one, they point to the
// same list-object, so the reference is only needed once.
public MovementAI(List<Gladiator> gladiatorsList) {
    this.gladiators = gladiatorsList;
}

// The class already has a reference to the list from its constructor so it
// doesn't need the list again as a parameter
public void moveAI() {

}

// If you don't want to keep a reference to the list in this class but only
// use it in a method (I would not recommend this)
public MovementAI() {

}

// You need to pass it gladiatorsList everytime you call this method.
public void moveAI(List<Gladiator> gladiators) {

}

}

我在你的上一条评论中看到你决定让AI决定重新制作它是否符合标准,不推荐,你应该在你的课堂上分开责任,减少错误和更好的发展。建议让AI更改角斗士列表(移动它们,杀死它们等),渲染器类只需绘制每个角斗士。

似乎你想让每个角斗士都能够把另一个角斗士作为目标,他们最好把目标作为一个对象,这样你就不必搜索整个列表了找出角斗士号所指的角斗士,你不必考虑在列表中进行排序。像这样:

public class Gladiator {
// ..other stuff

private Gladiator target;
public Gladiator getTarget() {
    return target;
}

public void setTarget(Gladiator target) {
    this.target = target;
}
}