因此,对于我正在创建的游戏,我有一些扩展GameDriver的类。
到目前为止,在所有其他课程中,我已经能够扩展GameDriver,然后在GameDriver中我可以做到:
ArrayList<Card> library = new ArrayList<Card>();
今天我开始使用GameAI课程,并扩展了GameDriver,当我放入:
GameAI Enemy = new GameAI();
在同一地点,我把另一行代码放在公共类GameDriver下面
我明白了:
java.lang.StackOverflowError
at java.util.WeakHashMap.expungeStaleEntries(Unknown Source)
at java.util.WeakHashMap.getTable(Unknown Source)
at java.util.WeakHashMap.get(Unknown Source)
at java.awt.Component.checkCoalescing(Unknown Source)
at java.awt.Component.<init>(Unknown Source)
at java.awt.Container.<init>(Unknown Source)
at java.awt.Panel.<init>(Unknown Source)
at java.awt.Panel.<init>(Unknown Source)
at java.applet.Applet.<init>(Unknown Source)
at GameDriver.<init>(GameDriver.java:14)
at GameAI.<init>(GameAI.java:8)
at GameDriver.<init>(GameDriver.java:40)
at GameAI.<init>(GameAI.java:8)
如果我将它放在applet的public void init()中,那么它在运行时不会出错,但是我无法通过其他方法访问它,我在看什么?所有的打火机通常都不会帮助我的大脑...
这就是GameAI现在的样子:
public class GameAI extends GameDriver {
public int life;
public int energy;
public void drawPhase(){
}
public GameAI(){
life = 20;
energy = 2;
}
}
然后是GameDriver的一些内容:
public class GameDriver extends Applet implements MouseMotionListener,MouseListener {
Graphics g;
Image offscreen;
Dimension dim;
int playerLife = 20;
int playerEnergy = 8;
int xMouse;
int yMouse;
int lineThickness = 4;
int handSize = 6;
int currentHover;
boolean slotHover;
int currentSelected;
boolean slotClicked;
int currentHoverBoard;
boolean slotHoverBoard;
boolean slotClickedBoard;
int currentSelectedBoard;
boolean canPlace;
ArrayList<Card> library = new ArrayList<Card>();
ArrayList<Card> hand = new ArrayList<Card>();
ArrayList<Card> playerBoard = new ArrayList<Card>();
GameAI Enemy;
int[] handBoxX = new int[handSize];
int[] handBoxY = new int[handSize];
int[] handBoxW = new int[handSize];
int[] handBoxH = new int[handSize];
int[] playerBoardX = new int[8];
int[] playerBoardY = new int[8];
int[] playerBoardW = new int[8];
int[] playerBoardH = new int[8];
public void init(){
this.setSize(640, 480);
dim = this.getSize();
addMouseMotionListener(this);
addMouseListener(this);
createLibrary();
drawFirstHand();
printHand();
GameAI Enemy = new GameAI();
checkEnemy();
offscreen = createImage(this.getSize().width,this.getSize().height);
g = offscreen.getGraphics();
}
public void checkEnemy(){
System.out.println(Enemy.energy);
}
... Alot more methods and stuff below, but nothing to do with the GameAI enemy
答案 0 :(得分:3)
你正在GameDriver中创建一个GameAI对象,它扩展了它的类。这将导致递归继续,直到内存不足。
解决方案:不要这样做。你的GameAI类不应该扩展GameDriver,因为这是分享信息的错误方式,即使你没有这种递归的噩梦,它也无法工作。而是给GameAI一个GameDriver字段,并通过其构造函数将GameDriver实例传递给GameAI。
即,
class GameAI {
private GameDriver gameDriver;
public GameAI(GameDriver gameDriver) {
this.gameDriver = gameDriver;
}
//.... more code
}
编辑2
如果你想要一个GameAI对象,你可以做
GameAI gameAi = new GameAI(this);
如果你想要一个数组或它们的列表,你就可以循环执行。