簡體   English   中英

從另一個類方法調用對象數組的特定成員

[英]Calling a specific member of an object array from another class-method

我現在在我項目的AI部分。 我正在從我的AI類中調用一個方法,該方法用於計算我繪制的Gladiator對象實際需要在哪里結束。 我將包含要放置的所有對象的列表傳遞給該方法。 AI類的先前方法已經確定了他們想要在距離上彼此相處的位置,我將其存儲為gladiator [0..1..2..etc] .movementGoal。

盡管該項目不是實時的,即我將只想“逐步”完成它,但我確實希望同時進行。 這意味着我無法遍歷列表的標准方法不起作用,因為我需要有關其他角斗士的移動決策的信息,以便找出這些角斗士在決策交互時的實際運動。

當我不在課堂上並且僅以列表形式使用它們時,如何訪問另一個特定的角斗士的變量?

編輯:

我想我可以遍歷並測試變量gladiatorNumber是否正確,那么什么時候提取該信息? 那將是非常好的回旋,但是我能想到的。

編輯2:

根據要求,提供一些代碼。 我在Ai類中的方法如下所示:

public void moveAI(List<Gladiator> gladiators) {

我的角斗士的定義如下:

public class Gladiator {

Gladiator類創建為數組,然后添加到單獨的主類的列表中。 我真的不想包含比這更多的代碼,因為有很多。 基本上,歸結為我該如何從AI類中調用gladiator [0],即使我在主類中創建了所述對象並且在AI類中僅以列表形式包含它們。 假設《角斗士》中的所有變量都是公共的。 我遇到的錯誤是找不到指向角斗士[0 ... 1 ... 2 ...等]的符號。

我認為您的問題歸結為想要將角斗士的數組傳遞給另一個類。 那應該很容易。 如果您在主類中有這兩個定義(請注意,您只需要一個定義,我建議您使用列表,因為它用途更多,數組具有固定長度)。

您想要這樣的東西:

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

}

人工智能

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更改角斗士的列表(移動它們,殺死它們等等),並且renderer類僅繪制每個角斗士。

似乎您還希望每個角斗士都可以將另一個角斗士作為目標,最好讓他們將目標作為對象,這樣您就不必搜索整個列表來找出哪個角斗士了。 gladiatornumber是指,您不必考慮列表中的順序。 像這樣:

public class Gladiator {
// ..other stuff

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM